biscofil/laravel-submodels

This package is abandoned and no longer maintained. No replacement package was suggested.

Create Laravel submodels

v2.0.1 2019-10-15 06:52 UTC

This package is auto-updated.

Last update: 2020-11-15 17:16:32 UTC


README

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.