difaneyami
difaneyami

Reputation: 51

Call to a member function addEagerConstraints() on null

I want to sort query in relation by type_order:

public function posts()
{
    if (($this->type_order) == '1') {
        $type = 'id';
        return $this->belongsToMany(Post::class, 'feed_posts')->orderBy($type);
    }
}

But get error:

FatalThrowableError
Call to a member function addEagerConstraints() on null

Upvotes: 5

Views: 10035

Answers (5)

Igor
Igor

Reputation: 1121

The only reason is that not everytime inside your Laravel relation method you can access to $this object, for example on re-rendering Livewire component - in your relation method $this object will be empty. In your case $this->type_order can be null and you don't have else statement, thats why Call to a member function addEagerConstraints() on null

Upvotes: 0

IQBAL AHMED
IQBAL AHMED

Reputation: 61

public function posts()
{
    if (($this->type_order) == '1') {
        $type = 'id';
        return $this->belongsToMany(Post::class, 'feed_posts')->orderBy($type);
    }
    return false;
}

Upvotes: 0

Zhong Huiwen
Zhong Huiwen

Reputation: 899

I had this issue because i forgot to return

class Test extends Model 
{
    public function tests(){
       $this->hasMany(Test::class);
    }
}

Upvotes: 27

Ajay Kumar
Ajay Kumar

Reputation: 1352

try use setType() kind of method to setting type then call like this $vaiable->setType()->posts;

public $newType = 'id'; // default ordering is by id

public function setType()
{
    if (($this->type_order) == '1') {
        $this->newType = 'id';
    }
    return $this;
}    

public function posts()
{
    $result = $this->belongsToMany(Post::class, 'feed_posts');
    return $result->orderBy($this->newType);
}

Upvotes: 0

Roj Vroemen
Roj Vroemen

Reputation: 1892

This happens because Laravel often creates an empty instance of your model to construct queries/new instances. So when it creates a new instance to build a query, posts() actually returns null instead of a BelongsToMany relation.

To fix this you'll have to remove the conditional and solve that issue in another way.

Upvotes: 1

Related Questions