Undefined offset 0 - Laravel

1

I have a list of users, each user has their 'role' (role / function inside the system, such as 'user' and 'admin') and this role has to be shown in the users list screen, which I I did it using the code block below.

@foreach ($users as $key => $user)
 <tr class="list-users">
  <td>{{ $user->id }}</td>
  <td>{{ $user->name }}</td>
  <td>{{ $user->email }}</td>
  <td>{{ $user->roles[0]->name }}</td>
 </tr>
@endforeach

The error occurs with this line <td>{{ $user->roles[0]->name }}</td> , indicating that 'roles' does not have index' 0 ', but when I do a dump {{ dd($user->roles[0]->name) }} , it returns me the variable normally (a string with the name' role 'of the user).

If I try to access using 'role' using {{ $user->roles()->first()->name }} the case is similar. With dd() working normally, but in @foreach of listing there is an error. The only difference is the type of error returned: 'Trying to get property 'name' of non-object ' .

What could be causing this?

    
asked by anonymous 20.09.2018 / 20:40

1 answer

3

Sometimes a user may not have a role defined, and even though by the question I understand that every user has a role , sometimes it could be the case that he was registered without a role .

I would suggest using the following code to make sure the user has some role :

{{ is_null($user->roles()->first()) ? 'Sem qualificação' : $user->roles()->first()->name }}

And a tip, if you are not using the with function when loading users, I would suggest using not to have to load this information at the time of displaying.

You just put the with('roles') function when loading users, here is the documentation, Eager Loading .

    
20.09.2018 / 21:03