I have two models: User and Tier. In my management rules, A user is associated with one or more Third Parties, and a Tier is associated with a single User.
Here is what I wrote in my template:
User Model
public function tiers(){
return $this->hasMany(Tier::class);
}
Tier Model
public function user(){
return $this->belongsTo(User::class,"user_id");
}
And when I try to retrieve the name of the User associated with the Tier as follows:
{{$tiers->user->name}}
But I have an error like this:
Attempt to read property "name" on null
does anyone have an idea, please?
2
Answers
The error message "Attempt to read property ‘name’ on null" suggests that the
user
relationship on theTier
model is returningnull
. This means that there is noUser
associated with theTier
in your database.You should check your database to ensure that the
user_id
foreign key in yourtiers
table is correctly set and points to an existingUser
.Also, before trying to access the
name
property on theuser
relationship, you should check if the relationship isnull
. Here’s how you can do this in your Blade template:In this code,
$tiers->user ? $tiers->user->name : 'No User'
checks if$tiers->user
is notnull
. If it’s notnull
, it outputs the user’s name. If it isnull
, it outputs ‘No User’.If the relation is defined properly and you’re facing issue Then you can simply tackle this error with the below approach:
Reference: https://gist.github.com/monish-khatri/1e526e419c1a1d8adc38a205a75cf536