lundi 12 juillet 2021

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>  </p>
@endforeach

This

<p>  </p>
or
<p>  </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 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?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire