0

What I want to do is quite simple I think. In my controller I have the code:

$list = SiteCategory::where('type','=','A')->get();

Which returns a standard eloquent collection object. However, sometimes when I retrieve categories, I want them to be ordered in a specific way first. So can I have some function in my model like:

Class SiteCategory extends Eloquent {

    public function mySpecialFunction(){
         // retrieve all categories, manipulate them in some way and return.
    }

}

How do I then call this function? I don't understand, and the tutorials and questions I've read do not help. For example, in this question on SO, he seems to imply he can call his function something like this:

SiteCategory->mySpecialFunction()

I don't get it?

Community
  • 1
  • 1
Inigo
  • 8,110
  • 18
  • 62
  • 110
  • why not just sort them after they've been retreived? if the sorting is done via a function, it will always be done after the database fetch either way. – Stefan Fisk Jan 24 '14 at 16:08
  • OK, so if I put this function in my model, then is it possible to chain it onto an eloquent call like siteCategory::All()->mySpecialFunction() Or do I have to declare it as a static function and call it separately? – Inigo Jan 24 '14 at 16:17
  • This question has an example of using a custom sort function: http://stackoverflow.com/questions/15533659/sorting-data-with-eloquent – Stefan Fisk Jan 24 '14 at 16:50
  • Thanks, Stefan, I've actually solved this now. The key was declaring $variable = new SiteCategory() then $variable->mySpecialFunction() in my controller, and accessing eloquent using $this within mySpecialFunction() – Inigo Jan 24 '14 at 17:16

1 Answers1

0

You can use a scope method inside your Model like this

Class SiteCategory extends Eloquent {

    public function scopeMySpecialFunction($query){
        // retrieve all categories, manipulate them in some way and return.
    }

}

Then you can call this function like normal built in Eloquent functions like

SiteCategory::mySpecialFunction();

If you want to pass any arguments into this function then you can add parameters like this

public function scopeMySpecialFunction($query, $param1, $param2){
    // retrieve all categories, manipulate them in some way and return.
}

Notice the first $query parameter, it's the first parameter of a scope method and $query is an instance of Illuminate\Database\Eloquent\Builder, you can use $this inside that function and can chain methods like

SiteCategory::mySpecialFunction()->find(1);

In this case you have to return the $query from your function to chain other methods, like:

public function scopeMySpecialFunction($query, $param1, $param2){
    // do something
    return $query;
}
The Alpha
  • 143,660
  • 29
  • 287
  • 307