Search code examples
laraveleloquentlaravel-8eloquent-relationship

How to override laravel model query?


I have a main model called User that returns all the users of the application.

There is a table called invites which manages the users invited to access the invitee panel. The invites table is thus linked to users:

enter image description here

So we have a general User model which handle all the users, and other two types of users:

  • Patient: user who invited the tenant
  • Tenant: user who has access to a list of associated patients

What I am trying to do is to fetch a patient list of a certain tenant (logged in user) using the eloquent relationship system, so I don't have to write a query for the join every time. Is it possible to do this?

At the moment, I tried this:

class Patient extends User
{
    use HasFactory;

    //protected $table = 'users';

    public function getList()
    {
        return $this->belongsToMany(User::class, 'invites', 'id', 'user_id');
    }
}

but of course this relationship not works because the query that should execute must be this:

SELECT u.* 
FROM users u
INNER JOIN invites i ON i.user_id = u.id 
WHERE i.tenant_id = 1

where id is the reference of the current user logged in which I retrieve using laratrust auth: auth()->user()->id.

Would be possible to return all the patients associated to the logged in user automatically? So simply calling:

Patient::query();

How can I achieve this?


Solution

  • To achieve that you should define relation and reverse many to many relation: in your user model:

    class Tenant extends User
    {
        use HasFactory;
    
        protected $table = 'users';
    
        public function patients()
        {
            return $this->belongsToMany(User::class, 'invites', 'tenant_id', 'user_id');
        }
    }
    

    And in Patient model define reverse many to many relation by reverse belongToMany params :

    class Patient extends User
    {
        use HasFactory;
    
        protected $table = 'users';
    
        public function tenants()
        {
            return $this->belongsToMany(User::class, 'invites', 'user_id', 'tenant_id');
        }
    }
    

    To use the auth id for each model you have 2 option:

    Option 1:

    add column in users table that named user_type wich have type enum('tenant','patient') and depend user type use the appropriate model

    Option 2:

    by using custom auth guards , take look to this article

    https://www.codecheef.org/article/laravel-8-login-with-custom-guard-example