Updated April 11, 2023
Introduction to Laravel Orderby
Laravel is one of the most popular frameworks and the reason is not unknown. It is easy to code and robust enough to scale. It provides the developer with enough options to make his/her tasks easier. Laravel also is compatible with other frameworks and hence is a delight to work with. Numerous affiliate frameworks integrate well with Laravel, case in point is the Sprite Billing system. Joins perfectly with Laravel Cashier to create a comprehensive Subscription management system.
There are plenty of examples that reflect on the flexibility and ease of usage of the framework. That is the reason why Laravel is also one of the most sought after eCommerce frameworks. Customers can simply scale up using the numerous methods and queries available in the library.
One of them is the numerously used Orderby.
What is Laravel Orderby?
Suppose you have a list of products with a host of sub-categories that you would want to view. It will become cumbersome if they all appeared haphazardly. You want order in a world of chaos. The query builder presents you with the command Orderby. Now things are in Order. You can view them by their names, their expiry dates (if it’s a perishable item). It can be anything. The important point is that the Orderby query lists the items in a defined order.
A quick example would be:
In a one to many relationships between the Categories and the Products, we intend to view the products but in an orderly manner. Preferably by their name. The Eloquent relationship will look like this:
Code:
class Category extends Model
{
public function products()
{
return $this->hasMany('App\Product');
}
}
However, the correct way of presenting it would be:
public function products()
{
return $this->hasMany('App\Product')->orderBy('name');
}
The Laravel Orderby promotes order about the parameters provided. In this case, “name”. Hence, the list that might appear thereafter will be in the form of the name of the products and no other details.
How does Laravel Orderby work?
The Laravel Orderby works by simply sorting the results of the query. So if the column has a list of 20 data, it can sort the list by the parameter provided. One can also create an order in an ascending or a Descending Order.
By Ascending Order:
$users = DB::table('users')->orderBy('name', 'asc')->get();
By Descending Order:
$users = DB::table('users')->orderBy('name', 'desc')->get();
Example #1
Step #1: This step is to provide some necessary queries
data: function() {
return {
newMList: { name: ''},
mLists: [],
orderToggle: 1,
orderAttr: 'name',
pagination: {
total: 0,
per_page: 10,
current_page: 1,
last_page: 0,
from: 1,
to: 10
}
}
}
Step #2: Additional Parameters are inserted as well as the Order by query
<tr v-for="mList in mLists | orderByorderAttrorderToggle">
<td>{{ mList.name }}</td>
<td>{{ mList.created_at }}</td>
<td>{{ mList.updated_at }}</td>
</tr>
Step #3: The template will now be inserted with sort buttons and named onClick
<tr>
<th>Name <button @click="changeSort('name')"><i class="fa {{ getSortIcon('name') }}"></i></button></th>
<th>Created <button @click="changeSort('created_at')"><i class="fa {{ getSortIcon('created_at') }}"></i></button></th>
<th>Updated <button @click="changeSort('updated_at')"><i class="fa {{ getSortIcon('updated_at') }}"></i></button></th>
</tr>
Step #4: Two new methods are now inserted. They are: change sort() and getSortIcon()
changeSort: function(attr) {
varorderToggle = ( this.orderAttr == attr ) ? this.orderToggle * -1 : 1;
this.fetchMLists(attr, orderToggle);
}
fetchMLists: function (orderAttr, orderToggle) {
varorderBy = orderAttr ?orderAttr : this.orderAttr;
var order = orderToggle ?orderToggle : this.orderToggle;
var progress = this.$Progress;
varmLists = [];
let params = {
perPage: this.pagination.per_page,
page: this.pagination.current_page,
orderBy: orderBy,
order: ( order == 1 ) ? 'asc' : 'desc'
};
this.$http.get(this.resourceUrl, {params : params}).then(function(response) {
if ( response.data&&response.data.data&&response.data.data.length ) {
this.$set('mLists', response.data.data);
this.orderAttr = orderBy;
this.orderToggle = order;
var pagination = {
total: response.data.total,
per_page: response.data.per_page,
current_page: response.data.current_page,
last_page: response.data.last_page,
from: response.data.from,
to: response.data.to
};
this.$set('pagination', pagination);
}
}, function(error) {
swal('An Error Occurred', 'Please refresh the page and try again.', 'error');
});
}
Output:
- Explanation: The Order By query sorts the Name parameter as per the instructions provided. The other option is by using the Sort Query. This does the same thing however there is a major difference between these two.
- Orderby influences the entire query set. That would primarily mean that the entire query set passes through the single reducer. Now, this is fine if the data set is short and sweet. But for larger data sets, this may take a longer time.
- Sort By does that through a local reducer. Hence a local ordering is done. Here each reducer’s output would be sorted. Total ordering will not be done across the entire dataset. However, it is going to be faster. That is a tradeoff many developers might want to make.
Example #2
Code:
SELECT
rep_name, rep_country, sales_volume,
rank() over (PARTITION BY rep_country ORDER BY sales_volume DESC) as rank
FROM
salesrep;
However, what makes orderBy() more efficient than sortBy() is because the former is essentially is trying to run a SQL query. Another example would be:
Code:
<?php
// Plan out a query to retrieve the posts alphabetized Z-A
// This is still a query and has not actually run
$posts = Posts::select('id', 'created_at', 'title')->orderBy('title', 'desc');
// Now the query has actually run. $posts is now a collection.
$posts = $posts->get();
// If you want to then sort this collection object to be ordered by the created_at timestamp, you *could* do this. This will run quickly with a small number of rows in the result but will be essentially unusable/so slow that your server will throw 500 errors if the collection contains hundreds or thousands of objects.
$posts = $posts->sortBy('created_at');
That said, Order by is a powerful query that influences a large query set. The cleaner the code or seamless the crossover, the quicker will be the query action. Again this has been the hallmark of Laravel as a whole. It aims to provide clear instructions through its library.
Conclusion
As with all of the Laravel queries, orderBy() helps in a seamless transition. It is an important query and helps in creating order out of insanity.
Recommended Articles
We hope that this EDUCBA information on “Laravel Orderby” was beneficial to you. You can view EDUCBA’s recommended articles for more information.