0

I made relationship between Film and Performer model.

Films model:

public function Performers()
{
    return $this->belongsToMany('App\Performer');
}

Performer model:

public function Films()
{
  return $this->belongsToMany('App\Films');
}

I've created table film_performer and relationship works, if I would add data manually.

I have a problem with saving data into film_performer after send form.

Into controller I attach it.

$film->performers()->attach($request->performers);

I don't have any errors. I used dd($request) to check array performers and everything is ok

linktoahref
  • 7,812
  • 3
  • 29
  • 51
komandir87
  • 33
  • 1
  • 6
  • Possible duplicate of [Laravel save / update many to many relationship](https://stackoverflow.com/questions/24702640/laravel-save-update-many-to-many-relationship) – Ilya Yaremchuk Feb 01 '18 at 08:43

1 Answers1

1

Change $request->performers to $request->performers->pluck('id') in:

$film->performers()->attach($request->performers)

The attach method expects an array of ids.

https://laravel.com/docs/5.5/eloquent-relationships#updating-many-to-many-relationships

For convenience, attach and detach also accept arrays of IDs as input:

$user = App\User::find(1);

$user->roles()->detach([1, 2, 3]);

$user->roles()->attach([ 1 => ['expires' => $expires], 2 => ['expires' => $expires] ]);