order by multiple columns in Laravel
order by multiple columns in Laravel
In this tutorial, we will try to find the solution to "order by multiple columns in Laravel" through programming.
Sometimes you have to run multiple order by in single query to get the records as per required order. You can use multiple order by in Laravel using orderBy() method on multiple columns.-
OrderBy method on multiple columns in laravel
$users = App\Models\User::orderBy('created_at', 'desc')->orderBy('id', 'asc')->get(); dd($users);
This code snippet will show data in order for columns created_at by DESC and with column id by ASC. It follows the first order by at first and second order by at second priority.
Demo code
Route::get('/order-by', function(){ $users = App\Models\User::orderBy('created_at', 'desc')->orderBy('id', 'asc')->get(); dd($users); });
Just copy/paste code in routes\web.php and visit http://localhost:8000/order-by after running the php artisan serve in command line.
Output :
^ Illuminate\Database\Eloquent\Collection {#1390 ▼ #items: array:14 [▶] }
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
Don't forget to share this article! Help us spread the word by clicking the share button below.
We appreciate your support and are committed to providing you valuable and informative content.
We are thankful for your never ending support.
Random Code Snippet Queries: Laravel
- Use of undefined constant laravel
- How to validate URL with https using regex in laravel
- Print last executed query in laravel
- How to check query string exists or not in laravel blade
- How to create event and listener in laravel ?
- Create user in Laravel using tinker
- Include External CSS and JS file in Laravel
- Return view from route Laravel
- How to create laravel project using jetstream
- Where to use whereNotNull eloquent in laravel
- Route [password.request] not defined
- How to generate .env file for laravel?
- Define variable and use in Laravel controller method
- Delete records with relationship in laravel
- How to send email in Laravel 11
- How to pass data to multiple partial view files in laravel
- How to call controller function from view in Laravel
- File_put_contents(/var/www/html/w3code/storage/framework/sessions/CXwN3EXKxERD6jgy3rADcaAAbAx8FRKih2JK7UO9): Failed to open stream: Permission denied
- Argument 1 passed to App\Http\Controllers\Auth\LoginController::authenticated() must be an instance of App\Http\Controllers\Auth\Request
- How to get laravel errors folder in views directory in laravel
- Rendering HTML from database table to view in Laravel
- Laravel 11 project setup on localhost using breeze with blade step by step
- How to pass data to route in laravel?
- SQLSTATE[42000]: Syntax error or access violation: 1055
- How to Get records between two dates in Laravel