Extend/override Eloquent create method - Cannot make static method non static

前端 未结 2 820
有刺的猬
有刺的猬 2021-01-02 01:17

I\'m overriding the create() Eloquent method, but when I try to call it I get Cannot make static method Illuminate\\\\Database\\\\Eloquent\\\\Model::creat

2条回答
  •  渐次进展
    2021-01-02 01:53

    As the error says: The method Illuminate\Database\Eloquent\Model::create() is static and cannot be overridden as non-static.

    So implement it as

    class MyModel extends Model
    {
        public static function create($data)
        {
            // ....
        }
    }
    

    and call it by MyModel::create([...]);

    You may also rethink if the auth-check-logic is really part of the Model or better moving it to the Controller or Routing part.

    UPDATE

    This approach does not work from version 5.4.* onwards, instead follow this answer.

    public static function create(array $attributes = [])
    {
        $model = static::query()->create($attributes);
    
        // ...
    
        return $model;
    }
    

提交回复
热议问题