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

kylemabaso's avatar

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.

0 likes
5 replies
kokoshneta's avatar

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.

pmieleszkiewicz's avatar
  1. On which line does error occur? Is it a problem with $user->client->name or $user->role->name?
  2. Do you use Spatie Permission package to handle roles and permissions?
  3. $user->role->name - do you have role or roles relation? Or both?
  4. You can debug your models with dd helper and check if there are any roles/client related to user.
kylemabaso's avatar

@pmieleszkiewicz Yes, I'm using Spatie. Sorry for the late response. I have posted a solution for future reference. I'm new to programming so I can't explain what it's doing but it works.

Snapey's avatar
Snapey
Best Answer
Level 122

one of your users does not have a client relation

use

<td>{{ $user->client->name ?? 'no client' }}</td>
2 likes
kylemabaso's avatar

I found a solution for those who come across a similar issue.

You get the roles within the controller like so:

	$users = User::with(['client', 'roles'])->get();

Then in blade:

	<td>{{ $user->client->name ?? 'None' }}</td>
	<td><span class="badge badge-success">{{ ucwords($user->roles[0]->name) ?? 'None' }}</span></td>

@snapey Your solution helped me get closer to solving the issue. Thank you to everyone for your help.

1 like

Please or to participate in this conversation.