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

lev89's avatar
Level 1

How to get data through pivot table?

users

  • $table->id();
  • $table->string('name');
  • $table->string('email')->unique();
  • $table->timestamp('email_verified_at')->nullable();
  • $table->string('password');
  • $table->rememberToken();

roles

  • $table->id();
  • $table->string('name');
  • $table->string('description')->nullable();
  • $table->string('permission')->nullable();

role_user

  • $table->id();
  • $table->unsignedBigInteger('user_id');
  • $table->unsignedBigInteger('role_id');
  • $table->foreign('user_id')->on('users')->references('id');
  • $table->foreign('role_id')->on('roles')->references('id');

User.php

class User extends Authenticatable
{
    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
}

Role.php

class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class);
    }
}

I need to get the name of the role for one user in Blade:

<p>Name: <strong>{{ auth()->user()->name }}</strong></p>
<p>Email: <strong>{{ auth()->user()->email }}</strong></p>
<p>Role: <strong>???</strong></p>
0 likes
1 reply
SilenceBringer's avatar

@lev89 as far as you have many-to-many relationship, you can have many roles assocaited with the user. So, to output every roles names

@foreach ($user->roles as $role)
<p>Role: <strong>{{ $role->name }}</strong></p>
@endforeach

or

<p>Role{{ $user->roles->count() > 1  ? 's' : '' }}: <strong>{{ $user->roles->pluck('name')->join(', ') }}</strong></p>

Please or to participate in this conversation.