'How to extend PHP Laravel model's fillable fields in a child class?
I try to extend an extintig ˙PHP` Laravel model with some other fields, but I not found the right solution. I use PHP 7.1 with Laravel 6.2
Here is my code, what explain what I want to do.
The original model:
<?php
namespace App;
use App\Scopes\VersionControlScope;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = [
'product_id',
'name',
'unit',
// ...
}
// ... relations, custom complex functions are here
}
And as I imagined how to extend the original model:
<?php
namespace App;
class ProductBackup extends Product
{
protected $fillable = array_merge(
parent::$fillable,
[
'date_of_backup',
]
);
// ...
}
But now I get Constant expression contains invalid operations
error message.
Can I extend shomehow my original model's $fillable
array in the child class?
Solution 1:[1]
In your subclass constructor, you may use mergeFillable
method from Illuminate\Database\Eloquent\Concerns\GuardsAttributes
trait (automatically available for every Eloquent model).
/**
* Create a new Eloquent model instance.
*
* @param array $attributes
* @return void
*/
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->mergeFillable(['date_of_backup']);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Shizzen83 |