Reputation: 597
I am very new to using pivot tables full stop never mind within Laravel, my apps have never been too complicated. Here is my issue.
I have setup a new test site, it has 3 tables.
users
roles
user_role
In the User model I have defined the relationship with the Role model as:
public function roles()
{
return $this->belongsToMany('App\Role');
}
Ok, so this should be easy enough I thought. First of all authenticating a user is simple
Auth::user();
Keeping this very simple all I really want to do is display the role or roles the user has. If I put this in a view:
Aith::user()->roles;
I get the following result
[{"id":"7","name":"Administrator","created_at":"2015-03-19 00:14:53","updated_at":"2015-03-19 00:14:53","pivot":{"user_id":"1","role_id":"7"}}]
Now that is spot on, however I will need to sound totally daft here. How do I just get it to return the role name?
Instead of the result above I just simply want it to display:
Administrator
Nothing more.
Upvotes: 3
Views: 4092
Reputation: 1074
either this to get the first record
Auth::user()->roles->first()->name
or use a loop
@foreach(Auth::user()->roles as $role)
{{ $role->name }}
@endforeach
Upvotes: 6