frontender_amsterdam
frontender_amsterdam

Reputation: 336

Laravel 7 multiselect in a one to many relationship

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

Answers (1)

Kristian
Kristian

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)
  • since you have defined the relationship between dashboard and tags (with belongsToMany function), you just need to get an array that contains all the tag IDs of the variable $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 array

Upvotes: 1

Related Questions