扩展/覆盖雄辩的创建方法 - 不能使静态方法非静态



我正在覆盖create() Eloquent 方法,但是当我尝试调用它时,我得到了Cannot make static method Illuminate\Database\Eloquent\Model::create() non static in class MyModel.

我像这样调用create()方法:

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

MyModel课上,我有这个:

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

为什么这不起作用?我应该更改什么才能使其正常工作?

正如错误所说:方法IlluminateDatabaseEloquentModel::create()是静态的,不能作为非静态重写。

所以实现它为

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

并按MyModel::create([...]);调用它

您还可以重新考虑身份验证检查逻辑是否真的是模型的一部分,或者更好地将其移动到控制器或路由部分。

更新

此方法从版本 5.4.* 开始不起作用,而是遵循此答案。

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

因为您正在覆盖它,并且在父类中它被定义为static 。尝试在函数定义中添加单词 static

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

当然,您还需要以静态方式调用它:

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

最新更新