'Attempt to read property "name" on null

Category Model

class Category extends Model
{
use HasFactory;

protected $fillable= ['name','number'];

 public function news(){

    return $this->hasMany(News::class);
}

News Model

class News extends Model
{
use HasFactory;

protected $fillable= ['cat_id','title','photo','description','author_id','status'];

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

  public function author(){
  return $this->belongsTo(Author::class);
    }

Author Model

class Author extends Model
{
use HasFactory;

protected $fillable= ['name','status'];

public function news(){
    return $this->hasMany(News::class);
}

There is a relationship between the 3 models. And I want to display category name instead of category_id in news-list.blade.php. I am getting a this error.

This is my controller function

  public function news_index(){
    $news= News::with('category')->get();
    return view('News.list',compact('news'));
}

This is my blade page. I got an error when I typed $new->category->name instead of cat_id.

@foreach($news as $new)
            <tr>
                <th scope="row">{{$loop->iteration}}</th>
                <td> {{$new->category->name}}</td>
                <td>  {{$new->title}}</td>
                <td> @if($new->photo)
                        <a href="{{url('storage/images/'.$new->photo)}}" target="_blank" class="btn btn-sm btn-secondary">Görüntüle</a></td>
                @endif
                </td>
                <td>  {{$new->author_id}}</td>
                <td>  {{$new->description}}</td>
                <td>  {{$new->status}}</td>

                <td>
                    <a class="btn btn-danger" onclick="return confirm('Silmek istediğinize emin 
       misiniz?')" href="{{route('news_delete', $new->id)}}"><i class="fa fa-trash"></i></a>
                    <a class="btn btn-primary" href="{{route('news_update',$new->id)}}"><i class="fa 
      fa-pen"></i></a>

                </td>
            </tr>
        @endforeach
 

Here is my news migration table

public function up()
    {
        Schema::create('news', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('cat_id');
            $table->string('title');
            $table->string('photo');
            $table->longText('description');
            $table->unsignedBigInteger('author_id');
            $table->boolean('status')->default('1');
$table->foreign('cat_id')->references('id')->on('categories')->onDelete('cascade');
            $table->foreign('author_id')->references('id')->on('authors')->onDelete('cascade');
            $table->timestamps();
        });
    }


Solution 1:[1]

You need to define your category foreign key explicitly while defining category relationships. Because your category foreign key is not category_id; it's cat_id.

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

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

Solution 2:[2]

I guess you need to rewrite you news_index() function.

public function news_index(){
    $news = News::with(array('category'=>function($query){
            $query->select('id','name');
        }))->get();
    return view('News.list',compact('news'));
}

i hope this will work. you were not assigning anything to $news variable and passing it to view. $new was null.

Solution 3:[3]

Check your tables. There has to be a match between the relationships.

Example:
users: id, book_id, name, email
books: id, title, price etc...

In the users table, the book_id, for example 5, must exist in books, otherwise the relationship will be lost and null errors will occur.

Solution 4:[4]

I had the same problem , and i solve it by this :

$new->category->name ?? None'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mrdev
Solution 2
Solution 3 ZygD
Solution 4 abdennour