Warm tip: This article is reproduced from stackoverflow.com, please click
laravel-5.8 php laravel-blade

How to populate a multiple selectpicker with old value in laravel

发布于 2020-03-27 10:24:51

I have an edit.blade.php(Post) where I have a multiple selectpicker that should show all categories(Category) and wich one is alredy 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 (thats the $categories) and the categories that post have are on $post->categories.

EDIT: Managed to get what I want but now I'm geting 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>
Questioner
Cristian
Viewed
62
Nazmul Abedin 2019-07-11 09:01

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