Chris Gmyr
Developer, entrepreneur, drummer, biker, dog owner, husband, and proud dad. Loves Laravel and coffee

How to order by all() in Laravel

05/24/2017

One common issue that I see with Laravel newcomers is that they have hangups using Eloquent correctly. The most basic reference given in the documentation and tutorials is using the all() method.

$users = User::all();

But what happens when you want to sort your users?

As a newcomers to the framework, I feel like most are too excited to “jump in and build something” instead of learning more about it. (But who can blame them, right?!?) So then something like this would happen:

$users = User::all()->orderBy('name', 'ASC');
# BadMethodCallException with message 'Method orderBy does not exist.'

// or

$users = User::orderBy('name', 'ASC')->all();
# BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::all()'

Forget about all()

In my experience, I’ve never needed an unordered dump of data in an application.

Note that all() is a convenience method for get() but does not allow you to chain additional methods. Take a look:

public static function all($columns = ['*'])
{
    return (new static)->newQuery()->get(
        is_array($columns) ? $columns : func_get_args()
    );
}

By using get() you’ll be able to achieve the desired results.

$users = User::orderBy('name', 'ASC')->get();

// and

$users = User::where('email', 'LIKE', '%@gmail.com')->orderBy('name', 'ASC')->get();

So any time you reach for the all() method, I highly recommend using get() instead.