Hi,
Looking for a bit of advance support on this as I am away from home and my PC and do not have any specific code to show.
In my past app I only had my as admin so authentication and users were easy. However I am advancing that to allow additional roles and users and using pivots for the first time.
On my test environment I created the users and roles table with a users_roles pivot and defined the belongsToMany relationship in public function roles, All fine. But I can’t get my head around displaying data from the pivot.
For example, I already have {{ Auth::user->name }} in my view to display the authenticated users name. But I want to also display the role or roles the user has. If I just display {{ Auth::users->roles }} that will return all the pivot contents and everything is correct so my setup is fine.
So how do I then for example extract from the pivot only the role for the authenticated user?
Thanks
Lee
Did you define the relationship in you models? From the Laravel documentation:
Many-to-many relations are a more complicated relationship type. An example of such a relationship is a user with many roles, where the roles are also shared by other users. For example, many users may have the role of "Admin". Three database tables are needed for this relationship: users, roles, and role_user. The role_user table is derived from the alphabetical order of the related model names, and should have user_id and role_id columns.
We can define a many-to-many relation using the belongsToMany method:
class User extends Model {
public function roles()
{
return $this->belongsToMany('App\Role');
}
}
Now, we can retrieve the roles through the User model:
$roles = User::find(1)->roles;
If you would like to use an unconventional table name for your pivot table, you may pass it as the second argument to the belongsToMany method:
return $this->belongsToMany('App\Role', 'user_roles');
You may also override the conventional associated keys:
return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'foo_id');
Of course, you may also define the inverse of the relationship on the Role model:
class Role extends Model {
public function users()
{
return $this->belongsToMany('App\User');
}
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community