Method 1: Laravel Eloquent orderBy Multiple Column
To define your orderBy in your model you can write it like below.
<?php Post::query() ->orderBy('published_at', 'ASC') ->orderBy('post_status', 'DESC') ->get();
SELECT * FROM `posts` ORDER BY `published_at` ASC, `post_status` DESC
Method 2: Using Order By Raw
You can also use orderByRaw method and it will accept the raw query.
Post::query() ->orderByRaw("published_at ASC, post_status DESC"); ->get();
Extra: Passing Array
You may also pass an array of ordering criteria and loop it through if you may want a complex ordering.
<?php $myTable->orders = [ ['column' => 'coloumn1', 'direction' => 'desc'], ['column' => 'coloumn2', 'direction' => 'asc'] ];
<?php $query = DB::table('my_tables'); foreach ($request->get('order_by_columns') as $column => $direction) { $query->orderBy($column, $direction); } $results = $query->get();
Leave a reply