2

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?

5
  • Just use simple inline if in input like this : @if($age==$nanny_babysitting_ages->age ) CHECKED @endif Commented Mar 29, 2017 at 9:04
  • @Saman Property [ages] does not exist on this collection instance. Commented Mar 29, 2017 at 9:08
  • 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(); Commented Mar 29, 2017 at 9:13
  • I am passing it from controller like I wrote in my question Commented Mar 29, 2017 at 13:17
  • So why age property dosent exists?? Commented Mar 29, 2017 at 14:15

2 Answers 2

4

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>
Sign up to request clarification or add additional context in comments.

Comments

0

you can use this "@checked(true)" like :- <input class="custom-control-input army" type="checkbox" id="customCheckbox1" @checked($emp_plus->army != 0)>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.