Reputation: 51
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
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
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
Reputation: 899
I had this issue because i forgot to return
class Test extends Model
{
public function tests(){
$this->hasMany(Test::class);
}
}
Upvotes: 27
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
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