Call to a member function addEagerConstraints() on null

Viewed 7608

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
5 Answers

I had this issue because i forgot to return

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

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

Related