Skip to main content
Tutorial Free

Model Default Ordering: Assigning a Global Scope

December 05, 2016
1 min read
Quite an often situation in real-life projects that you have to order lists by a certain condition. For example, countries/cities in alphabetical order everywhere. Is there a way to avoid adding "orderBy" every time we make a list for a dropdown? Apparently, it's pretty easy - we can use Global Scopes. Let's say we have a model City with field name, and we need to order all the lists by name. Here's what function we add to our model - we override a boot() method:
protected static function boot()
{
    parent::boot();

    // Order by name ASC
    static::addGlobalScope('order', function (Builder $builder) {
        $builder->orderBy('name', 'asc');
    });
}
Also we need to add this on top:

use Illuminate\Database\Eloquent\Builder;

Ok, so what do we see here? Method addGlobalScope is getting anonymous function as a parameter, where we actually tell the system what condition to add to all operations with Query Builder. In reality, if you call City::all() from this point, it will actually execute this query:

select * from cities order by name asc

For more complex situations, you can change that anonymous function to a separate Scope class and pass it as a parameter, see official documentation here.

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

PR
Pratik Rane ✓ Link copied!

Thank you Povilas! This is exactly what I wanted. I'm always amazed to see how you cover such nitty-gritty things in Laravel.

PR
Pratik Rane ✓ Link copied!

I wish laravel model had some option like this though, what do you think?

/**
* The column name to order by the models.
*
* @var string
*/
public $orderBy = "created_at";
 
/**
* The direction to order by the models.
*
* @var string
*/
public $orderByDirection = "desc";

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.