简体   繁体   中英

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?

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']);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM