Skip to content

Instantly share code, notes, and snippets.

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
You can’t perform that action at this time.