简体   繁体   中英

Eloquent does not recognize fillable fields when adding constructor to model

I have model Category as below:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    /**
     * @var $fillable
     */
    protected $fillable = array('title', 'slug' , 'descriptoin', 'cover', 'logo', 'parent_id');

    /**
     * @var $category_logo_pathp
     */
    protected $category_logo_path ;

    /**
     * @var $category_cover_path
     */
    protected $category_cover_path ;

    /**
     * constructor
     */
    function __construct()
    {
        $this->category_cover_path = public_path() . '/upload/image/category/cover/';
        $this->category_logo_path = public_path() . '/upload/image/category/logo/';
    }

    /**
     * relation with itself
     */
    public function parent()
    {
        return self::where('id', $this->parent_id)->first();
    }

    public function coverPath()
    {
        return $this->category_cover_path;
    }

    public function logoPath()
    {
        return $this->category_logo_path;
    }
}

When inserting a category instance with correct data into database , Eloquent does not recognize fillable fields of the model and then throws Illuminate\\Database\\QueryException but when i remove the constructor from category model , it works fine and fillable fields are recognized using Eloquent. what is causing this?

For sure, you should run parent constructor and probably it's quite reasonable to use default Model signature, so your constructor should look like this:

public function __construct(array $attributes = [])
{
   parent::__construct($attributes);
   $this->category_cover_path = public_path() . '/upload/image/category/cover/';
   $this->category_logo_path = public_path() . '/upload/image/category/logo/';
}

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