unkind_sauce1
unkind_sauce1

Reputation: 548

How can I fix this error "Trying to get property 'title' of non-object" in laravel 8

Background: I installed a new Laravel version 8.49.2, and moved my app logic (controllers, routes, views, middlewares, models, custom configs) from (a legacy Laravel v5.8 project), Everything works well as expected so far.

But when I access a relationship attribute in blade I get the following error: Trying to get property 'title' of non-object (View: /Path/to/resources/views/users.blade.php)

Blade:

@foreach($users as $user)
<p> {{ $user->roles->title }} </p>
@endforeach

This

<p> {{ $user['roles']['title'] }} </p>
or
<p> {{ $user->roles['title'] }} </p>

Also gives the error Trying to access array offset on value of type null

The Controller:

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

User Model:

public function roles()
{
    return $this->belongsTo(Role::class, 'levelId'); 
}

Role Model:

    public function users()
{
    return $this->hasMany(User::class, 'levelId');
}

When I die and dump dd($user->roles->title) I get the value "Admin" But just echoing it like so {{ $user->roles->title }} gives the error.

NOTE: When I change my PHP version to 7.3, this does not give an error. But in PHP 7.4.20 or 7.4.21 this error occurs. But I need PHP 7.4.* Does anyone know how I can solve this?

Upvotes: 0

Views: 7342

Answers (1)

John Lobo
John Lobo

Reputation: 15319

Look like some users doesn't have role .So better check for null.When you dd($user->roles->title) it only check for first user record not for all users.

@foreach($users as $user)
<p> {{ $user->roles->title??null }} </p>
@endforeach

Upvotes: 3

Related Questions