Call to a member function addEagerConstraints() on null laravel8

Viewed 14

i want fetch two tables data using with() but getting error as "Call to a member function addEagerConstraints() on null "

I have author model with multiple post relationship

My model relation as follows as follows:

Post relationship :

class Post extends Model
{
    use HasFactory;
    public function author(){
        $this->belongsTo(Author::class);
    }
}

Author model as follows:

class Author extends Model
{
    use HasFactory;
    public function post(){
       return $this->hasMany(Post::class);
    }
    
}

my migration of post table as follows:

Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('cat');
            $table->timestamps();
            $table->unsignedBigInteger('author_id');
            $table->foreign('author_id')->references('id')->on('authors');
        });

I am trying to fetch data in controller as follows using with() in postcontroller

public function index(){
        return $data = Post::with('author')->get();
        
    }

But getting error as Call to a member function addEagerConstraints() on null . Anyone have idea what is wrong in that then please let me know.

1 Answers

Can you try adding a return statement;

class Post extends Model
{
    use HasFactory;
    public function author(){
        return $this->belongsTo(Author::class);
    }
}
Related