Create submodels in Laravel
Via Composer
composer require biscofil/laravel-submodels
>>> 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());
}
}
license. Please see the license file for more information.