Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

Im trying to load my model in my controller and tried this:

return Post::getAll(); 

got the error Non-static method Post::getAll() should not be called statically, assuming $this from incompatible context

The function in the model looks like this:

public function getAll() {      return $posts = $this->all()->take(2)->get();  } 

What's the correct way to load the model in a controller and then return it's contents?

like image 488
Sam Pettersson Avatar asked Aug 20 '13 15:08

Sam Pettersson


People also ask

Why is it illegal for static method to invoke a non static method?

A non-static method is a method that executes in the context of an instance . Without an instance it makes no sense to call one, so the compiler prevents you from doing so - ie it's illegal.

Can static methods invoke non static methods?

A static method can only access static data members and static methods of another class or same class but cannot access non-static methods and variables. Also, a static method can rewrite the values of any static data member.

How non static method is invoked?

But when we try to call Non static function i.e, TestMethod() inside static function it gives an error - “An object refernce is required for non-static field, member or Property 'Program. TestMethod()”. So we need to create an instance of the class to call the non-static method.

Can I call a static method inside a regular method?

If you have no object but just call a static method and in that method you want to call another static method in the same class, you have to use self:: . So to avoid potential errors (and strict warnings) it is better to use self .


1 Answers

You defined your method as non-static and you are trying to invoke it as static. That said...

1.if you want to invoke a static method, you should use the :: and define your method as static.

// Defining a static method in a Foo class. public static function getAll() { /* code */ }  // Invoking that static method Foo::getAll(); 

2.otherwise, if you want to invoke an instance method you should instance your class, use ->.

// Defining a non-static method in a Foo class. public function getAll() { /* code */ }  // Invoking that non-static method. $foo = new Foo(); $foo->getAll(); 

Note: In Laravel, almost all Eloquent methods return an instance of your model, allowing you to chain methods as shown below:

$foos = Foo::all()->take(10)->get(); 

In that code we are statically calling the all method via Facade. After that, all other methods are being called as instance methods.

like image 82
Rubens Mariuzzo Avatar answered Sep 17 '22 18:09

Rubens Mariuzzo