skip to Main Content

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


  1. The error message "Attempt to read property ‘name’ on null" suggests that the user relationship on the Tier model is returning null. This means that there is no User associated with the Tier in your database.

    You should check your database to ensure that the user_id foreign key in your tiers table is correctly set and points to an existing User.

    Also, before trying to access the name property on the user relationship, you should check if the relationship is null. Here’s how you can do this in your Blade template:

    {{ $tiers->user ? $tiers->user->name : 'No User' }}
    

    In this code, $tiers->user ? $tiers->user->name : 'No User' checks if $tiers->user is not null. If it’s not null, it outputs the user’s name. If it is null, it outputs ‘No User’.

    Login or Signup to reply.
  2. If the relation is defined properly and you’re facing issue Then you can simply tackle this error with the below approach:

    1) {{$tiers->user?->name}}
    2) {{optional($tiers->user)->name}}
    
    

    Reference: https://gist.github.com/monish-khatri/1e526e419c1a1d8adc38a205a75cf536

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search