Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[6.0] Add the ability to order by subqueries #29563

merged 1 commit into from Aug 14, 2019


Copy link

commented Aug 14, 2019

This PR adds the ability to order by subqueries using the existing orderBy($column, $direction = 'asc') and orderByDesc($column) methods.

Previously this was only possible using orderByRaw(), but that's dangerous, as the direction (asc/desc) cannot be set with a binding, meaning developers were responsible for verifying and inserting the direction into the query themselves.

Here are a couple examples of how this can be useful.

// Order users by their last login date
$users = User::orderBy(function ($query) {
        ->whereColumn('user_id', '')

// Order courses by the start date of the first lesson
$courses = Course::orderBy(
        ->whereColumn('course_id', '')

Note, orderBy() now accepts subqueries in three possible formats:

  • Illuminate\Database\Query\Builder
  • Illuminate\Database\Eloquent\Builder
  • Closure

This is the exact same approach as what's done in the whereIn() method:

if ($values instanceof self ||
$values instanceof EloquentBuilder ||
$values instanceof Closure) {
[$query, $bindings] = $this->createSub($values);
$values = [new Expression($query)];
$this->addBinding($bindings, 'where');

@reinink reinink force-pushed the reinink:order-by-sub-queries branch from e79b13a to 8c994c3 Aug 14, 2019

@taylorotwell taylorotwell merged commit acbbfea into laravel:master Aug 14, 2019

2 checks passed

continuous-integration/styleci/pr The analysis has passed
continuous-integration/travis-ci/pr The Travis CI build passed

@reinink reinink deleted the reinink:order-by-sub-queries branch Aug 14, 2019

@GrahamCampbell GrahamCampbell changed the title Add the ability to order by subqueries [6.0] Add the ability to order by subqueries Aug 14, 2019


This comment has been minimized.

Copy link

commented Aug 14, 2019


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet
3 participants
You can’t perform that action at this time.