Question

I started studying Laravel and ran into a problem using models. How to load them? For example in CodeIgniter i used it like $model = $this->load->model('some_model'). In Laravel when i call it from controller like Sites::OfUser() it work fine, but when i call Sites::getId() it says that method should be static... Is it possible to call method without static or i need to create facades for each model?

My model looks like this:

namespace Models;

use Eloquent;

class Sites extends Eloquent {

    public function scopeOfUser($query)
    {}

    public function getId($name)
    {}
}
Was it helpful?

Solution

For static method--

$type = Sites ::scopeOfUser($query);

and if you want normal like codeingiter then use--

$model = new Sites ();
$type = $model->scopeOfUser($query);

OTHER TIPS

You can of course make a static method in the model, and do some static work in it (get ID for name or whatever).

That's no problem.

However, you must declare it static if you want to use the ::, which you are doing not.

public static /* <-- this */ function getId($name)
{
    // Do work
    // return $result;
}

If you want to access a method with ::, you will need to make it a static method or create a Facade.

The reason why Sites::OfUser() is "working" is because you have prefixed that method with scope.

Scopes allow you to easily re-use query logic in your models. To define a scope, simply prefix a model method with scope.

If you want to use Facades you can follow my answer here on how to create a Facade.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top