Ari Grimm
Ari Grimm

Reputation: 13

Laravel form checkbox data

I have two tables; both of which have several columns. In one, I have all licenses the user can select (with checkboxes), in the other I store what licenses the user has.

I created a model to get all licenses, and model to get what licenses the user has.

Now, I can't understand how to create a view of all licences where those that the user already has are already checked - e.g when I create the form with these checkboxes, how can I check if the user already has the license.

I can get values but I cannot get the @if syntax work.

Here is my code currently:

<div class="form-group col-sm-12">
    <div class="form-check form-check-inline">
        @foreach($all_license as $all_licen_row)
            @foreach($drive_licenses as $lisen)
                @if($lisen->license_id==$all_licen_row->id)

                    <input class="form-check-input" type="checkbox"
                           name="{{$all_licen_row->license_id}}" checked>

                    <label class="form-check-label"
                           for="inlineCheckbox1">{{ $all_licen_row->class }}</label>)

                @else
                    <input class="form-check-input" type="checkbox" name="{{$all_licen_row->license_id}}">

                    <label class="form-check-label"
                           for="inlineCheckbox1">{{ $all_licen_row->class }}</label>)
                @endif
            @endforeach
            @if($errors->has('id'))
                <span class="help-block">
                <strong class="text-danger">{{ $errors->first('drive_licence') }}</strong>

            </span>
            @endif
        @endforeach

    </div>
</div>

Upvotes: 1

Views: 479

Answers (1)

JPark
JPark

Reputation: 789

Something like this is usually easier to handle without using an inner loop. You can check which id's should be selected before looping through $all_license by just storing the ids from drive_licenses into an array and simply check if the $all_license id exists in the array. Example:

<?php 
    $ids = array();
    foreach($drive_licenses as $lisen) {
        array_push($ids, $lisen->license_id)
    }
?>
@foreach($all_license as $all_licen_row)
    @if(in_array($all_licen_row->id, $ids))

        <input class="form-check-input" type="checkbox" name="{{$all_licen_row->license_id}}" checked>
        <label class="form-check-label" for="inlineCheckbox1">{{ $all_licen_row->class }}</label>

    @else
        ...
    @endif
@endforeach

If you want, you could also use the ternary operator (e.g., (?:)) to shorten your code some. Example:

@foreach($all_license as $all_licen_row)

    <input class="form-check-input" type="checkbox" name="{{$all_licen_row->license_id}}"{{ (in_array($all_licen_row->id, $ids) ? ' checked' : '') }}>
    <label class="form-check-label" for="inlineCheckbox1">{{ $all_licen_row->class }}</label>

@endforeach

Upvotes: 1

Related Questions