Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mbasfour's avatar

Login a user and assign him a model based on a role field on the users table

Hi, I am trying to create a custom login, where after logging in the user gets assigned a custom model that inheritance the default User model based on a "role" field on the users' table, the reason is that each model has its own relations.

I started by adding custom guards:

'teacher' => [
            'driver' => 'session',
            'provider'=> 'teachers',

        ],

 'student'=> [
            'driver' => 'session',
            'provider'=> 'students',
        ]

and providers:

'teachers' => [
            'driver' => 'eloquent',
            'model' => App\Teacher::class,
        
        ],
'students' => [
            'driver' => 'eloquent',
            'model'=> App\Student::class,
        ],

I don't exactly know what to do next, how to create a custom controller that assign a logged in user a Teacher or Student based on the "role" field of the users table?

0 likes
6 replies
rawilk's avatar

Why not make it a relation on your user model?

If you have a role_id on your user table, you could do something like this on your User model:

// you can name this function whatever
public function group()
{
    switch ($this->role_id) {
        case 1: // or whatever id belongs to teacher role
            return $this->belongsTo(Teacher::class);
        case 2:
            return $this->belongsTo(Student::class);
        default:
            dd($this->id);
    }
}
1 like
mbasfour's avatar

@wilk_randall good answer, I can do this for shared relations, but each model has its own additional relations.

mbasfour's avatar

@FlorinFratica I implemented the code? how to make the user model use a Teacher model instance to get its relations after the user logs in?

FlorinFratica's avatar

@mbasfour You would have to create the Teacher instance. Something like this:

if (auth()->user()->is_teacher) {
    $user = Teacher::find(auth()->id());
    dump($user->teacherSpecificRelationship);
}

Please or to participate in this conversation.