I'm using Laravel 8, and having many-to-many relationship using custom pivot model as explained here in the documentation. However, I don't know how can I access the methods that I have created inside the custom pivot model.
Let's say, using the example provided in the doc, I created some methods inside the RoleUser
model. My question is: how can I access those methods from Role
model, from something like Role::find(1)->users()
? Is it possible?
Thank you in advance!
CodePudding user response:
Same as accessing any attribute from pivot.
https://laravel.com/docs/8.x/eloquent-relationships#retrieving-intermediate-table-columns
use App\Models\User;
$user = User::find(1);
foreach ($user->roles as $role) {
echo $role->pivot->methodInPivot();
}
CodePudding user response:
In Role model define the relationship.
class Role extends Model
{
public function users()
{
return $this->belongsToMany(User::class);
}
}
Important: piot table must be singular format and sorted by alphabetic order. ex
role_user
.
If you defied as
roles_user
, you need a custom mapping in the user relationship in the role model.
In Controller
public function funcName()
{
# You can use all the Eloquent methods like where, get, first etc...
$roles = Role::with('users')->get();
return view('view_name', compact('roles'));
}
In View
foreach($roles as $role)
{
Role name - {{$role->name}}
foreach($role->users as $user)
{
user name - {{$user->name}}
}
}
To access any additional field inside the pivot table, you can use the
->pivot
prefix. Ex$user->pivot->created_at