Skip to content

Instantly share code, notes, and snippets.

@amochohan
Created March 6, 2017 12:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amochohan/2a3def80adba2e5ed15f0d2bcd89d2c0 to your computer and use it in GitHub Desktop.
Save amochohan/2a3def80adba2e5ed15f0d2bcd89d2c0 to your computer and use it in GitHub Desktop.
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