What is User->roles(), and how does it relate to $user->role->name? The name of the relation makes it look like it gets a collection of roles, but that’s not what you’re calling in the view.
Mar 20, 2022
5
Level 3
Attempt to read property "name" on null
Hi Guys. I'm trying to get the role and client name on the user's list but I get an error stating "Attempt to read property "name" on null". Below's my code:
@foreach($users as $user)
<tr>
<td>{{ $user->firstname }}</td>
<td>{{ $user->lastname }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->client->name }}</td>
<td><span class="badge badge-success">{{ $user->role->name }}</span></td>
</tr>
@endforeach
My User model is like this:
use HasApiTokens, HasFactory, Notifiable, HasRoles;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'firstname',
'lastname',
'email',
'password',
'client_id'
];
public function client()
{
return $this->belongsTo(Client::class);
}
User Controller
public function index()
{
$users = User::with('roles', 'client')->get();
return view('system.users.index', compact('users'));
}
Then migration
$table->foreignId('client_id')->nullable();
I'm not sure as to what I'm missing.
Level 122
one of your users does not have a client relation
use
<td>{{ $user->client->name ?? 'no client' }}</td>
2 likes
Please or to participate in this conversation.