I have lists of "risks" (which are like accounts).
A User may have one of many roles for that risk (eg. admin=1, user=2, viewer=3)
The IDs for each role is stored in a "roles" table.
This is all captured in my many to many table, users_risks_roles
For example: from three users, two (users 1 and 2) have 'admin' rights (role_id 1) and one user has 'user' rights (role_id 2), all on the same risk (risk_id 1)
user_id risk_id role_id
1 1 1
2 1 1
3 1 2
Currently, on the show risk view, I can list out each user and his or her associated role's ID for that risk (eg, 1,2,3).
How do I pull in the role name and description? (Eg 1 = admin)?
Code:
Risk Model
class Risk extends Model
{
public function users() {
return $this->belongsToMany(User::class,'users_risks_roles')->withPivot('role_id');
}
public function roles() {
return $this->belongsToMany(Role::class,'users_risks_roles')->withPivot('role_id');
}
Show Risk View
@foreach ($risk->users as $user)
<tr><td>{{ $user->name }}</a></td>
<td>{{$user->email}}</td>
<td>{{$user->phone}}</td>
<td>{{$user->pivot->role_id}}</td></tr>
@endforeach
I want to display something like
$user->pivot->role->role_name
$user->pivot->role->role_description
Note: I have done this using a DB:Select SQL query using joins, but am curious how I could structure this in Eloquent. SQL looks something like this
RiskController
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
...
$user = Auth::user();
$users = DB::select('select * from users u join users_risks_roles urr join roles r where u.id = urr.user_id and r.id = urr.role_id and u.id = :id', ['id' => $user->id]);