Skip to content

Instantly share code, notes, and snippets.

@amochohan
Created March 6, 2017 12:03
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Ordering Eloquent results
<?php
// Instead of using the following code
$builder = User::with('somerelationship');
if ($request->has('order_by')) {
$builder->orderBy($request->input('order_by'));
}
$users = $builder->get();
// Use 'when' to remove the conditional
$users = User::with('somerelationship')->when($request->has('order_by'), function ($query) use ($request) {
return $query->orderBy($request->input('order_by'));
})->get();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment