Extend / override Eloquent create method - Unable to make the static method non-stationary

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

I call the create() method as follows:

 $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 is this not working? What should I change to make it work?

+6
source share
2 answers

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

So implement it like

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

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

You can also rethink if the authentication logic is indeed part of the model or it is better to transfer it to the controller or routing part.

UPDATE

This approach does not work since version 5.4. *, Follow this answer instead.

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

Probably because you override it and in the parent class it is defined as static . Try adding the word static to the 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 also need to call it in a static way:

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

Source: https://habr.com/ru/post/956088/


All Articles