
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
- How to add script on specific view file in laravel while extending layout
- How to get session in blade Laravel ?
- How to implement toggleLike() method in Overtrue\LaravelLike laravel package
- Call to undefined function Illuminate\Encryption\openssl_cipher_iv_length()
- How to call Laravel route in jQuery
- Comment .env file in laravel
- Delete records with relationship in laravel
- How to get laravel errors folder in views directory in laravel
- Define variable and use in Laravel controller method
- Trying to get property 'title' of non-object
- How to create belongstomany relation using custom name on custom pivot table
- Redirect to another view from controller in laravel
- Method Illuminate\Database\Eloquent\Collection::appends does not exist
- How to use bootstrap pagination in laravel 8
- Route prefix with auth middleware in laravel
- Laravel create multiple records in Pivot table
- How to send ID to another page in Laravel
- Laravel get single row by id
- How to use more than one query scope in Laravel
- Remove several global scope from query
- Get previous date data in laravel
- How to get the id of last record from collection object in laravel view
- Laravel route parameter
- Session Doesn't Work on Redirect
- Target class [admin] does not exist.