Home > Software engineering >  Laravel 8 - Call to a member function addEagerConstraints() on null
Laravel 8 - Call to a member function addEagerConstraints() on null

Time:12-02

I have a user model that can be a client or a provider. What I need is to load a different relation depending on what type of user it is

If the user is a Client, I must load their relationship with my client model, and exactly the same in the case of being a provider

To do this, I first get the personal data with the person relationship (which works as expected) and then I try to load the conditional relationship as shown below

$users = User::with('person')->get();
$users->load('entity');

But in my browser, i receive this error

Error Call to a member function addEagerConstraints() on null

This is the function of my relationship

public function entity() {

    switch($this->type) {

        case 'Client': 
            return $this->hasOne(Client::class,'id','client_id');
        break;

        case 'Provider':
            return $this->hasOne(Provider::class,'id','provider_id'); 
        break;

    }

}

CodePudding user response:

That's because some of your users are not of type Client or Provider, therefore and because of how you defined the entity() relationship, it may doesn't exist for some of them.

Avoid any conditional within your relationships and consider using polymorphic relationships for this scenario since your User model can be related to more than 1 Model class.

You could simplify your model and database by using entitable_id and indentitable_type within your users table and defining your relatiionship such as:

Entity.php model

public function entitable()
{
     return $this->morphTo();
}

----------------------------

Users.php model

public function entity()
{
    return $this->morphOne(Entity::class, 'entitable');
}

EDIT: If you want to keep it this way, you can try something like mapping $users

$users = $users->map(function($user){
     return $user->type == 'Client' || $user->type == 'Provider' ? $user->load('entity') : $user;
});
  • Related