0
votes

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

2
Forget your own implementation, use package, instead. Good luck.Kyslik
thanks, but have any example using PivotModel @KyslikAl-Amin
No, I do not get why you want to re-invent the wheel... if this is only for educational purposes than its acceptable.Kyslik
yes i want learnAl-Amin

2 Answers

0
votes

I'm pretty sure $model->pivot will give you access to whatever data is in the relevant pivot table entries, regardless of what that table is called or whether you have a model class for it, so long as your model relationship methods are set up as many-to-many.

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.