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>
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
both are objects can't use in_array in_array() expects parameter 2 to be array, object given
You can convert the object to array by using toArray() $post->categories->pluck('id')->toArray(), this will convert the object to array
works perfect but I don't understand the code, would be cool if you explain a bit, thanks!
you can look at the laravel helpers, laravel.com/docs/5.8/helpers, to see the helper function, @if(in_array($category->id, $post->categories->pluck('id')->toArray())) here i am using the if condition in blade file so its @if, and $category->id , is your id of the category object, $post->categories->pluck('id')->toArray(), is code, first, $post->categories, gives you the post categories in object from, then i use the pluck('id') to get the only id, from the categoris, and then i use toArray() to convert it to array, so that I can check category id available or not, hope it helps you