phplaraveleloquent

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


I tried to load my model in my controller and tried this:

return Post::getAll();

and I still get 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 its contents?


Solution

  • 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.