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

前端 未结 2 808
有刺的猬
有刺的猬 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;
    }
    
    0 讨论(0)
  • 2021-01-02 01:57

    Probably because you are overriding it and in the parent class it is defined as static. Try adding the word static in your function definition:

    public static function create($data)
    {
       if (!Namespace\Auth::isAuthed())
        throw new Exception("You can not create a post as a guest.");
    
       return parent::create($data);
    }
    

    Of course you will also need to invoke it in a static manner:

    $f = MyModel::create([
        'post_type_id' => 1,
        'to_user_id' => Input::get('toUser'),
        'from_user_id' => 10,
        'message' => Input::get('message')
    ]);
    
    0 讨论(0)
提交回复
热议问题