Laravel 12, you can sort query results using Eloquent’s `orderBy` method. Sorting is a common operation when retrieving data from the database, and Eloquent makes it easy to sort results by one or more columns.
Below are examples of how to sort query results using Eloquent in Laravel 12.
Basic Sorting with `orderBy`
The `orderBy` method allows you to sort the results by a specific column in ascending or descending order.
Example: Sort Users by Name in Ascending Order
```php use App\Models\User; $users = User::orderBy('name', 'asc')->get();
Example: Sort Users by Created Date in Descending Order
```php use App\Models\User; $users = User::orderBy('created_at', 'desc')->get();
Sorting by Multiple Columns
You can chain multiple `orderBy` methods to sort by multiple columns.
Example: Sort Users by Name (Ascending) and Created Date (Descending)
```php use App\Models\User; $users = User::orderBy('name', 'asc') ->orderBy('created_at', 'desc') ->get();
Dynamic Sorting Based on User Input
If you want to dynamically sort results based on user input (e.g., from a request), you can pass the column and direction as parameters.
Example: Dynamic Sorting
```php use App\Models\User; use Illuminate\Http\Request; public function index(Request $request) { $column = $request->input('sort_by', 'name'); // Default to 'name' $direction = $request->input('sort_dir', 'asc'); // Default to 'asc' $users = User::orderBy($column, $direction)->get(); return view('users.index', compact('users')); }
In this example:
– The `sort_by` parameter specifies the column to sort by.
– The `sort_dir` parameter specifies the direction (`asc` or `desc`).
Sorting Related Models
If you want to sort results based on a related model’s column, you can use the `join` method or the `with` method with a custom query.
Example: Sort Posts by User Name
```php use App\Models\Post; $posts = Post::join('users', 'posts.user_id', '=', 'users.id') ->orderBy('users.name', 'asc') ->select('posts.*') // Select only posts columns ->get();
Alternatively, you can use Eloquent relationships with a custom query:
```php use App\Models\Post; $posts = Post::with(['user' => function ($query) { $query->orderBy('name', 'asc'); }]) ->get();
Sorting with Pagination
If you’re using pagination, you can still apply sorting.
Example: Sort Users by Name and Paginate
```php use App\Models\User; $users = User::orderBy('name', 'asc')->paginate(10);
Sorting with Conditional Logic
You can add conditional logic to your sorting based on specific criteria.
Example: Conditional Sorting
```php use App\Models\User; $users = User::when($request->has('sort_by'), function ($query) use ($request) { return $query->orderBy($request->input('sort_by'), $request->input('sort_dir', 'asc')); }) ->get();
Sorting by Raw Expressions
If you need to sort by a raw SQL expression, you can use the `orderByRaw` method.
Example: Sort by a Calculated Field
```php use App\Models\User; $users = User::orderByRaw('LENGTH(name) DESC')->get();
Complete Example
Here’s a complete example of a controller method that sorts users dynamically and paginates the results:
```php use App\Models\User; use Illuminate\Http\Request; public function index(Request $request) { // Default sorting column and direction $column = $request->input('sort_by', 'name'); $direction = $request->input('sort_dir', 'asc'); // Validate sorting direction $direction = in_array(strtolower($direction), ['asc', 'desc']) ? $direction : 'asc'; // Fetch sorted and paginated users $users = User::orderBy($column, $direction)->paginate(10); return view('users.index', compact('users')); }
Blade View Example
In your Blade view, you can display the sorted results and provide links for sorting:
```html <table> <thead> <tr> <th><a href="{{ request()->fullUrlWithQuery(['sort_by' => 'name', 'sort_dir' => $sortDir === 'asc' ? 'desc' : 'asc']) }}">Name</a></th> <th><a href="{{ request()->fullUrlWithQuery(['sort_by' => 'email', 'sort_dir' => $sortDir === 'asc' ? 'desc' : 'asc']) }}">Email</a></th> <th>Created At</th> </tr> </thead> <tbody> @foreach ($users as $user) <tr> <td>{{ $user->name }}</td> <td>{{ $user->email }}</td> <td>{{ $user->created_at->format('Y-m-d') }}</td> </tr> @endforeach </tbody> </table> {{ $users->links() }}
Points
1. Use `orderBy` for simple sorting.
2. Chain multiple `orderBy` methods for sorting by multiple columns.
3. Use `orderByRaw` for complex sorting logic.
4. Combine sorting with pagination for better performance.
5. Dynamically adjust sorting based on user input.