[Solved] Attempt to read property "name" on null - belongsTo relationship in Laravel

Laravel Mohaimen Khalid

Problem:  we got an error when tried to create a relationship with a category table and then I try to show category name then I got an error -

attempt to read property "name" on null

Here is the News model relationship function - 

public function category(){
  return $this->belongsTo(Category::class);
}

try to show - 

{{ $news->category->name }}

Now I discuss how I solved this problem.


Solution:

we need to define our category foreign key explicitly while defining category relationships. Because of category foreign key is not category_id. it's cat_id. if I use category_id as a foreign key then laravel automatically defines the relationship with the category table. That's why we have manually declared foreign key property names.

For example, We need to define the category relationship in News model like below:

public function category()
{
    return $this->belongsTo(Category::class, 'cat_id');
}

Thank you for reading the article. If you face any problems, please comment below.