Using Scopes in Laravel

Posted: 2014-05-16 20:28:21

I have about 4 models that all share 2 common queries. I want all of them that are "Published" and or Ordered by a field called Order.

This does help with some DRY goals, but you could easily change or add to a scope as needed to update all the queries involved etc. Especially if at a later point you break this out into a Repository Patter to use a different ORM.

So using Scopes I can make one shared query. All my Model classes extend a BaseModel class I made that looks like this

//app/models/BaseModel.php
<?php

class BaseModel extends \Eloquent {

    public function scopePublished($query)
    {
        return $query->where("published", "=", 1);
    }

    public function scopeOrderByOrder($query)
    {
        return $query->orderBy('order');
    }
} 

So with any of the three class all I have to do is use these scopes.

//app/controllers/PortfoliosController.php
    public function adminIndex()
    {
        $portfolios = Portfolio::OrderByOrder()->get();

        return View::make('portfolios.admin_index', compact('portfolios'));
    }

or even a Models relationships

//app/models/Portfolio.php

    public function projects()
    {
        return $this->hasMany('Project')->Published()->OrderByOrder();
    }