I had this problem where I had to get all the names from one table and get relation from another table and check if the relationship exists or not and if it exists, the checkbox must be checked.

Let me clear the problem first.

I need to show all the categories of the posts. So I used a foreach loop to get all the category’s names. Now I had another table that stores the post-categories relation. I have to check that table if the relation already exists or not. For this, at first what I did was used another loop inside the foreach loop which checks if the fk_category_id on the relationship table matches with the one in the main table and check if exists.

@foreach($categories as $category)
   
            <input class="" type="checkbox" id="{{$category->category_id}}" value="{{$category->category_id}}"
            @foreach($selectedCategories as $selectedCategory)
                    @if($selectedCategory->fk_category_id == $category->category_id)
                        checked
                    @endif
                    @endforeach>
              
            <label for="{{$category->category_id}}">
                {{$category->category_name}}
            </label>
@endforeach

But this made my query run multiple times which will eventually slow down the speed if the categories and relations are more. Therefore, there is a simpler solution for this.

{{isset($selectedCategories) ? (in_array($cateogry->category_id, array_values($selectedCategories->categories->pluck('fk_category_id')->toArray())) ? 'checked' : '') : ''}}
            

The total code becomes like this

@foreach($categories as $category)
   
            <input class="checkbox_id" type="checkbox" id="{{$category->category_id}}" value="{{$category->category_id}}"
           {{isset($selectedCategories) ? (in_array($cateogry->category_id, array_values($selectedCategories->categories->pluck('fk_category_id')->toArray())) ? 'checked' : '') : ''}}>
              
            <label for="{{$category->category_id}}">
                {{$category->category_name}}
            </label>
@endforeach

This decreases the number of queries executed and also increases the page speed overall.

Hope this helps.