Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 206
Marwelln Avatar asked Oct 16 '13 12:10

Marwelln


2 Answers

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;
}
like image 101
HenningCash Avatar answered Sep 22 '22 13:09

HenningCash


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')
]);
like image 43
Glad To Help Avatar answered Sep 20 '22 13:09

Glad To Help