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

Daniel-Pablo's avatar

Please some help trying to access ROLES

Please community help with this code, On the controller am sending this data

  public function index()
  {
    $users = User::all();
    return view('/user.index', compact('users'));
  }

On the view I cant call the roles with this code

{{ $user->roles->first()->id }}

// got this error => Trying to get property of non-object I got to suspend it

        @foreach($users as $user)
        <tr>
            <td>{{$user->id}}</td>
            <td>{{$user->name}}</td>
            <td>{{$user->email}}</td>
            {{-- <td>{{$user->roles->first()->name}}</td> --}}
            {{ $user->roles->first()->id }}
            <td><a href="/user/{{$user->id}}"><i class="fas fa-eye"></i> Ingresar</a></td>
            @endforeach

BUT when I call that same last code on the SHOW view it runs

$user->roles->first()->id

how i can call it? the ROLES...

am calling them this way on the class User extends Authenticatable

    public function roles()
    {
        return $this->belongsToMany(Role::class); // nombre del modelo
    }

thanks to the laravel community

0 likes
2 replies
Nakov's avatar
Nakov
Best Answer
Level 73

So the error says that you are trying to use the name when the roles return null for some reason. So is there a user that doesn't have a role in the database assigned? Because first() returns null if there are no roles for a user.

show works because that user has a role, but when you list all the users it can fail on any user that doesn't have a role.

So you can query the users that have at least one role maybe

$users = User::whereHas('roles')->with('roles')->get();
Daniel-Pablo's avatar

Thank you!! @nakov I go to the database and there is a NULL field that was the error!! thanks

Please or to participate in this conversation.