biscofil / laravel-submodels
Create Laravel submodels
Installs: 16 598
Dependents: 0
Suggesters: 0
Security: 0
Stars: 4
Watchers: 0
Forks: 0
Open Issues: 2
Requires
- illuminate/database: ~5.6.0|~5.7.0|~5.8.0|^6.0.0
Requires (Dev)
- orchestra/testbench: 3.8.*
- phpunit/phpunit: ^7.0
This package is auto-updated.
Last update: 2020-11-15 17:16:32 UTC
README
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.