Home > Software engineering >  Attempt to read property "id" on null Laravel 8 eloquent
Attempt to read property "id" on null Laravel 8 eloquent

Time:06-11

I have a query that fetches comments of posts. It returns this error when a particular post has no comments. Below is my query.

$comments=PostComments::with('user:id,username')
            ->where('post_id',$this->id)->latest()->get();

This is my Comments model

    protected $table = "post_comments";
    protected $fillable = ['comment','post_id','user_id'];
    protected $hidden = ["updated_at","laravel_through_key","post_id"];
    // Carbon instance fields
    protected $dates = ['created_at', 'updated_at'];

    public function user(){
        return $this->hasMany(User::class,'id','user_id')->latest();

CodePudding user response:

Your $this must be null. You could show a screenshot of the error where it will show you the line where the error occurred, which would make debugging it easier.

  • Related