Reputation: 336
I am trying to get the selected saved values of my multi select, without success.
I have the following code:
public function tag()
{
return $this->belongsToMany(Tag::class, 'tags_dashboard', 'dashboard_id', 'tag_id');
}
I want the selected values to be selected. This does not seem to work:
<select id="tags" name="tags[]" class="form-control" multiple>
@foreach($tags as $tag)
<option value="{{$tag->id}}" @foreach($tags as $dashboard->tag) {{ in_array($tag->id, $dashboard->tag) ? "selected" : null }} @endforeach>{{$tag->name}}</option>
@endforeach
</select>
It gives the error in_array() expects parameter 2 to be array, object given
Upvotes: 0
Views: 364
Reputation: 2505
You have the logic correct there, it's just syntax/notation problem
In place of:
in_array($tag->id, $dashboard->tag)
Use:
in_array($tag->id, $dashboard->tag()->pluck("tags.id")->toArray())
Explanation:
$tag->id
returns the ID (int from database)$dashboard
$dashboard->tag()
returns the relationship between $dashboard and its tags$dashboard->tag()->pluck("tags.id")
returns a laravel collection object that holds all tag IDs of $dashboard's tags$dashboard->tag()->pluck("tags.id")->toArray()
: the last toArray function convert a laravel collection object to php native arrayUpvotes: 1