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?
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.
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With