I want to manage user and role by PivotModel like User belongsToMany roles and Role belongsToMany users, so the pivot model name PivotModel that extends Pivot, how to make relation with PivotModel and User , get data from PivotModel like as PivotModel with users where role_id=1
0
votes
2 Answers
0
votes
0
votes
Don't make a Model for your Pivot; it's unnecessary. If you have Models for both Role and User, you can define the relationships as:
// User Model
public function roles(){
return $this->belongsToMany(Role::class, $table, $foreignKey, $localKey);
}
// Role Model
public function users(){
return $this->belongsToMany(User::class, $table, $foreignKey, $localKey);
}
Just make sure to substitute $table
, $foreignKey
and $localKey
with values. Laravel can figure them out if your table/column names are consistent (roles_users
, user_id
, role_id
, id
, etc)
Then, if there's any data you want to access from the pivot rows, add
return $this->belongsToMany(...)->withPivot(["column_1", "column_2", ...]);
Then, you may access these using the ->pivot->{column}
accessor:
foreach($user->roles AS $role){
dd($role->pivot->column_1); // Etc.
}
There are plenty of packages that do this for you, such as Cartalyst Sentinel (https://cartalyst.com/manual/sentinel/2.0), so have a look at those for more information.