Cristian
Cristian

Reputation: 382

How to populate a multiple selectpicker with old value in Laravel

I have an edit.blade.php(Post) where I have a multiple selectpicker that should show all categories(Category) and which one is already selected. After some research I found this method to make it works but it says in_array() expects parameter 2 to be array, null given

<select class="form-control selectpicker" multiple name="category[]" title="Categoría">
  @foreach($categories as $category)
        <option value="{{ $category->id }}" {{ (in_array($category, old("category")) ? "selected":"") }} >{{ $category->name }}</option>
  @endforeach
</select>

I'm sending from my PostController all the existing categories from a trait (that's the $categories) and the categories that post have are on $post->categories.

EDIT: Managed to get what I want but now I'm getting multiple copies of the values, any way to avoid this?

<select class="form-control selectpicker" multiple name="category[]" title="Categoría">
                                @foreach ($categories as $category)
                                    @foreach ($post->categories as $postCategory)
                                        @if ($postCategory->id == $category->id)
                                            <option selected value="{{ $category->id }}">{{ $category->name }}</option>
                                        @else
                                            <option value="{{ $category->id }}">{{ $category->name }}</option>
                                        @endif
                                    @endforeach
                                @endforeach
                            </select>

Upvotes: 1

Views: 1054

Answers (1)

Nazmul Abedin
Nazmul Abedin

Reputation: 157

You can use like this, for post categories, pluck the id, and check in the array, or from the controller, you can pass the array of the post categories as well,

  @foreach ($categories as $category)
         <option @if(in_array($category->id, $post->categories->pluck('id')->toArray())) selected 
         @endif value="{{ $category->id }}">{{ $category->name }}</option>                
    @endforeach

Upvotes: 1

Related Questions