Skip to content
Advertisement

How to check only stored checkbox value in database in laravel?

I’m facing a problem that all checkboxes are checked. I want only the checkbox which has a value in database to be checked.

I have these three tables where place_category is the pivot table 
-------  --------------   ----------
places  place_category    categories 
------  --------------    ----------
id         place_id           id
name       category_id        name

eloquent relationships are set.
Here I'm trying to associate many categories for one place but I want only the categories that I added to that place to be checked in the checkbox.
...........

 @foreach($categories as $category)
    <div class="col-lg-3">
         <div class="form-group">

           <input type="checkbox" name="category[]" value="{{$category->id}}" {{isset($category) ? 'checked': '' }} >{{ $category->name }}<br>
                                        </div>
                                </div>

 @endforeach

Is there any problem with my condition ? {{isset($category) ? ‘checked’: ” }}

Advertisement

Answer

The problem is that your $category will always be set this way, it will always return true.

You are probably iterating over all the categories, so you need to compare the category with for example the product or whatever you have in the view, and check if the category id is the one selected for that product.. something like this:

@foreach($categories as $category)
<div class="col-lg-3">
    <div class="form-group">
        <input type="checkbox" name="category[]"
           value="{{$category->id}}"
           @if($category->id === $model->category_id) 'checked' @endif>
           {{ $category->name }}<br>
    </div>
</div>
@endforeach

Now this code will check the category only if it was attached to the model that you are listing. Show more code from the controller maybe and the view to get better help if this is not sufficient for you.

— EDIT

Based on your edit, you are using a many to many relationship there.. so this will do it:

@if($place->categories->contains($category->id)) 'checked' @endif
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement