Saving many-to-many relationships, synchronization / binding does not exist?

I have the following two two models in a many-to-many relationship:

use Illuminate\Database\Eloquent\Model; class Permission extends Model { /** * The database table used by the model. * * @var string */ protected $table = 'permissions'; /* |-------------------------------------------------------------------------- | Relationship Methods |-------------------------------------------------------------------------- */ /** * many-to-many relationship method * * @return QueryBuilder */ public function roles() { return $this->belongsToMany('App\Admin\Role'); } } 

and

 class Role extends Model { /** * The database table used by the model. * * @var string */ protected $table = 'roles'; /* |-------------------------------------------------------------------------- | Relationship Methods |-------------------------------------------------------------------------- */ /** * many-to-many relationship method. * * @return QueryBuilder */ public function users() { return $this->belongsToMany('App\Admin\User'); } /** * many-to-many relationship method. * * @return QueryBuilder */ public function permissions() { return $this->belongsToMany('App\Admin\Permission'); } } 

What I'm trying to do here is to create a page where you can create a new role, and associate this role with the permissions already created:

 @foreach ($permissions as $permission) <label class="checkbox"> <input type="checkbox" value="{{ $permission->id }}" name="permissions[]" id="permission_{{ $permission }} }}"> {{ $permission->permission_title }} </label> @endforeach 

and in the controller I tried this to extract the selected permissions from the page and save everything:

 // logic to save role $role->save(); $permissions = Input::get('permissions'); $role->permissions->sync($permissions); 

However, after executing the last statement, I get the following error: exception 'BadMethodCallException' with message 'Method sync does not exist. "I get the same error for attach . Also, I'm not sure if I have to specify the name of the permission_role staging table somewhere? Thanks.

+5
source share
1 answer

You need to use the following:

 $role->permissions()->sync($permissions); 

Do not forget ()

EDIT: A few more explanations:

$role->permissions - an instance of the collection.

$role->permissions() is an instance of belongsToMany that contains the sync() method

+12
source

Source: https://habr.com/ru/post/1244518/


All Articles