If Only I Knew That!

Webby things that could save you time

Laravel 4 ORM query scope

without comments

It’s been a while and 2 frameworks later from Codeigniter, I’m using the Laravel 4 with composer. Life’s got a lot easier and quicker. Here is a quick snippet, that I’ll reference at some stage.

ORM query scope has been added to Laravel 4. It’s as simple as this

class User extends Eloquent {

     public function scopeApproved($query)
     {
          $query->where('approved', 1);
     }

    public function scopePopular($query)
    {
          $query->where('votes', '>', 100);
     }

}

and to use the query

$users = User::approved()->popular()->get();

If you want to pass additional parameters to the query

class User extends Eloquent {

     public function scopeApproved($query)
     {
          $query->where('approved', 1);
     }

    public function scopePopular($query, $minimum = 100)
    {
          $query->where('votes', '>', $minimum);
     }

}

and to use it

$users = User::approved()->popular(50)->get();

Original info is here

Written by admin

March 22nd, 2013 at 7:44 am

Posted in Laravel

Leave a Reply

Powered by CDN Rewrites