Search code examples
phplaraveljquery-select2jquery-select2-4

How to select some multiple options by default using select2 and Laravel


I have tables in the database as follows.

resumes

id    name    phone 



categories 

id   catName 

Then i have a pivot table to store many to many reltionship

category_resume 

category_id    resume_id

Now i have a edit Resume view where i want to display all the stored categories for specific resume. i am using select2 plugin for select boxes.

i have tried this so far

<select class="select2" multiple="true">
        @foreach($categories as $category)
       <option {{$category->id == $resume->categories->category_id ? 'selected':''}}> 
          {{$category->catName}}
       </option>
        @endforeach
</select>  

unfortunately, this is giving me an error because $resume->categories is a collection and i can not access it like this $resume->categories->category_id. i need to use foreach here. But my question is how can i make my select box selected with related categories on load?

Thanks.


Solution

  • The reason you cannot compare $category->id with $resume->categories->category_id is as you say the latter will give you a collection and you really need just to check that the $category->id exists within an array of selected ids.

    You should create the array in your controller before passing it to the view;

    Something like:

    public function show($id) 
    {
       $resume = Resume::findOrFail($id);
       $selectedCategories = $resume->categories->pluck('id')->toArray();
    
       return view('resume.view', compact('resume', 'selectedCategories');
    
    }
    

    Then in your view do;

    <select class="select2" multiple="true">
            @foreach($categories as $category)
           <option {{in_array($category->id, $selectedCategories) ? 'selected':''}}> 
              {{$category->catName}}
           </option>
            @endforeach
    </select>  
    

    Also, it is sensible to check that $categories is not empty before foreaching it.

    @if(! empty($categories)) 
        @foreach($categories as $category)
        ...
        @endforeach
    @endif