Extend/override Eloquent create method - Cannot ma

2020-06-12 03:44发布

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

I call the create() method like this:

$f = new MyModel();
$f->create([
    'post_type_id' => 1,
    'to_user_id' => Input::get('toUser'),
    'from_user_id' => 10,
    'message' => Input::get('message')
]);

And in the MyModel class I have this:

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

    parent::create($data);
}

Why doesn't this work? What should I change to make it work?

2条回答
\"骚年 ilove
2楼-- · 2020-06-12 04:30

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;
}
查看更多
乱世女痞
3楼-- · 2020-06-12 04:49

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')
]);
查看更多
登录 后发表回答