
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
- Laravel csrf token mismatch for ajax POST Request
- How to send email in Laravel 11
- Pagination in laravel
- How to Run CRON Job on LIVE SERVER on Cpanel in Laravel Project
- How to randomly get the user id from users table in laravel
- Laravel 10 starter app using breeze on live server
- The use statement with non-compound name 'Auth' has no effect
- Wheredate in laravel not working
- How to get images from AWS s3 and display in Laravel blade
- Get today records in Laravel
- Datetime field in Laravel migration
- Multiple Level eager loading in Laravel
- Cast Array to an Object in Controller and then pass to view in laravel
- How to add background image to div using Tailwindcss, Vite in Laravel Environment
- How to pass two variables in HREF in laravel
- How to add foreign key in laravel using migration
- Laravel create default admin user
- Create model with migration and seeder
- Get content from web URL in laravel
- Class "App\Http\Controllers\Auth\Verified" not found
- Fatal error: Uncaught Error: Class "Illuminate\Foundation\Application" not found
- Method Illuminate\Http\Request::validated does not exist
- Laravel 10 Breeze Authentication Example
- Eager loading dynamically in laravel
- Best Practices for Error Handling in Production Server Code (example code)