Undefined offset 0 - Laravel

Asked

Viewed 1,557 times

1

I have a list of users, each user has their 'role' (role/function within the system, such as 'user' and 'admin') and this role has to be shown on the user listing screen, which I did 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

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

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

What could be causing this?

  • How you’re passing $users to the page?

  • Yes. @sant0will

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 may be the case that it 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 hint, if not using the function with when loading users, I would suggest using to not have to upload this information when displaying.

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

  • 1

    Exactly that, thank you. the last user of the list did not have a 'role' defined for him and so the error occurred. dd() displayed the dump only from the first record, which is from the administrator and it has a defined role. So in dd() it worked normally, but not in the list.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.