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

mstnorris's avatar

User model inheritance

I would like to extend the User model to simplify login and to separate different relationships between shared models.

I've included my setup below. I am having difficulties in how I should access the logged in User's modules / module depending on whether they are a Student or a Teacher.

User model

This is the generic (untouched) User model.

Student model

<?php

namespace App;

class Student extends User
{

    public function modules()
    {
        return $this->belongsToMany(Module::class);
    }
}

Teacher model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Teacher extends Model
{
    public function module()
    {
        $this->hasMany(Module::class);
    }
}

Module model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Module extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'module_code',
        'name',
        'description',
        'color'
    ];

    public function students()
    {
        return $this->belongsToMany(Student::class);
    }

    public function teacher()
    {
        return $this->belongsTo(Teacher::class);
    }
}
0 likes
2 replies
PLB-RR's avatar

Don't know if it is possible with the default user model, but maybe worth a try to morph it to either a student or a teacher.

mstnorris's avatar

I've just been trying that already and so far it is what I'm after button sure how it will hold up when it gets more complicated. I'm probably over thinking things.

Please or to participate in this conversation.