Created
March 6, 2017 12:03
-
-
Save amochohan/2a3def80adba2e5ed15f0d2bcd89d2c0 to your computer and use it in GitHub Desktop.
Ordering Eloquent results
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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