Laravel belongsToMany get one record

Viewed 891

I have three tables as below:

users id|name|username|password

roles id|name

users_roles id|user_id|role_id

These tables communicate via belongsToMany. Table users_roles has many records. The user can change his role, but I have to store every change.

id user_id role_id
1 2 2
1 3 2
1 2 3

1st. How can I get the last and single role_id with the user?

$users = User::with('roles')->get();

Now I'm getting user(2) with two roles, but I need user(2) with single and last role(3).

2nd. How I can access roles->name on the blade?

@foreach($users as $user)
    {{ $user->name }} <<< normal
    {{ $user->roles['name']}}  <<I'm getting error here  
2 Answers

roles will be a collection so you could just use the last() method and have something like:

$user->roles->last()->name;

Alternatively, if you can update to Laravel >= 8.42, you could use the Has one of many relationship.

Create a new relationship in your User model:

public function latestRole()
{
    return $this->hasOne(Role::class)->latestOfMany();
}

Then you would load the role with latestRole:

$users = User::with('latestRole')->get();

This way you can access the relationship directly:

@foreach($users as $user)
    {{ $user->latestRole->name }}

You can use whereHas

 $users = User::with('roles')->whereHas('roles', function ($q) {
        $q->latest();
    })->get();
Related