2
votes

I am trying to set checkboxes checked based on database value. One user can have have multiple checkbox values.

Checkboxes are generated from database table called child_age_groups:

   @foreach ($child_age_groups as $age)
      <div class="checkbox checkbox-info checkbox-inline">
         <input class="age_group_checkbox" type="checkbox" name="age_group[]" id="age_group{{$age->id}}" "/>
        <label for="age_group{{$age->id}}">{{$age->age_group}}</label>
     </div>
  @endforeach

So in my controller I get all the options that user has like this

  $nanny_babysitting_ages      = Nanny_babysitting_ages::where('user_id', user()->id)->get();

My nanny_babysitting_ages table is this

user_id | ages

and my child_age_groups table where I populate the checkboxes are this:

id | age_group

How can I set the checkboxes selcted based on the values from database?

1
Just use simple inline if in input like this : @if($age==$nanny_babysitting_ages->age ) CHECKED @endif - Saman
@Saman Property [ages] does not exist on this collection instance. - z0mbieKale
this is dirty work but if not passed $nanny_babysitting_ages from controller you can get $nanny_babysitting_ages in view with something like : /App/Nanny_babysitting_ages::where('user_id', user()->id)->get(); - Saman
I am passing it from controller like I wrote in my question - z0mbieKale
So why age property dosent exists?? - Saman

1 Answers

2
votes

This is how I resolved it, I added foreach and if statement in the input to check if it the same value as from database:

             <div class="form-group" id="ageCheckboxes">
                @foreach ($child_age_groups as $age)
                <div class="checkbox checkbox-info checkbox-inline">
                   <input class="age_group_checkbox" type="checkbox" value="{{$age->id}}" name="age_group[]" id="age_group{{$age->id}}" @foreach ($nanny_babysitting_ages as $ages) @if($age->id == $ages->ages ) checked @endif @endforeach />
                   <label for="age_group{{$age->id}}">{{$age->age_group}}</label>
                </div>
                @endforeach
             </div>