Monday, April 3, 2017

Eloquent model inheritance hierarchy

I have a case where 2 eloquent models should inherit properties from a User model, but the User itself should not exist as a standalone instance. (Mentors and Students, both inherit from User class). So what I'm currently doing is:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

abstract class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * Get the courses that the user has enrolled into
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */

    public function courses()
    {
        return $this->hasMany('App\Models\Course', 'user_course', 'user_id', 'course_id');
    }
}

class Student extends User
{
    protected $table = 'students';

    /**
     * Get the mentors that the user has hired
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */

    public function mentors()
    {
        return $this->hasMany('App\Models\User');
    }
}

class Mentor extends User
{
    protected $table = 'mentors';

    /**
     * Get a list of courses that a mentor is teaching
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */

    public function ownCourses()
    {
        return $this->hasMany('App\Models\Course', 'mentor_course', 'mentor_id', 'course_id');
    }
}

I am wondering whether this is the correct to do what I am trying to accomplish?



via kjanko

Advertisement