Skip to content
This repository has been archived by the owner on Oct 20, 2020. It is now read-only.

biscofil/laravel-submodels

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

40 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Laravel Submodels

Latest Version on Packagist Travis Total Downloads Coverage Status

Create submodels in Laravel

Installation

Via Composer

composer require biscofil/laravel-submodels

Usage

>>> User::find(1)
=> App\AdminUser {#3182
     id: 1,
     first_name: "something",
     last_name: "something"
     is_admin: true,
     admin_parameter: "something"

>>> User::find(2)
=> App\User {#3164
     id: 2,
     first_name: "something",
     last_name: "something",
     is_admin: false

In order to accomplish this result, each Model that has to be extended must implement getSubModelClass that returns the right class depending on conditions.

class User extends Authenticatable{

    use HasSubModels;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'first_name', 'last_name', 'is_admin'
    ];

    /**
    * @param $model
    * @return string|null
    */
   public function getSubModelClass($model){
       $class = null;
       if ($model->isAdmin()) {
           $class = AdminUser::class;
       } elseif ($model->isCustomer()) {
           $class = CustomerUser::class;
       }
       return $class;
   }

   /**
     * @param $query
     * @return mixed
     */
    public function scopeAdmins($query)
    {
        return $query->where('is_admin', '=', true);
    }

}

On the other side, each sub model can add the appendedFillable PRIVATE property that contains the list of fillable parameters. This list will be merged with the list of the parent class. The same happens for the appendedCasts array.

class AdminUser extends User{

    use HasAppendedFields;

    private $appendedFillable = [
        'admin_parameter',
        'is_a_cool_admin'
    ];

    private $appendedCasts = [
         'is_a_cool_admin' => 'bool'
    ];

    public function newQuery()
    {
        return $this->scopeAdmins(parent::newQuery());
    }

}

Credits

License

license. Please see the license file for more information.