Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

peet's avatar
Level 1

How can I access model data from an intermediary table pivot that provides the model id?

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]);
0 likes
2 replies
burlresearch's avatar

In order to do what you want, I think you have to look down to Defining Custom Intermediate Table Models section.

NB that class must extend Illuminate\Database\Eloquent\Relations\Pivot

You are very close, but the last relationship you want, namely $user->pivot->role, would be a relation from your intermediary table.

So by building the class as described, you may then add the needed relation functions: public function role() { return $this->belongsTo(Role::class); }

peet's avatar
Level 1

Thank you, will give it a shot

Please or to participate in this conversation.