orderByRaw Method In Laravel
Tags: laravel, sorting, webdev, orderbyraw
Published: 2023-02-27 04:59:10

The **orderByRaw** method allows you to specify a raw SQL expression to use for sorting the results of a query. This can be useful when you need to sort by a calculated value, a complex expression, or a column that is not directly available in the database.

Here's an example that demonstrates how to use orderByRaw in Laravel.

## Example # 1 

```
$users = DB::table('users')
    ->orderByRaw('LENGTH(name) DESC')
    ->get();
```

In this example, we first select all columns from the users table using the table method of the DB facade.

We then use the orderByRaw method to specify a raw SQL expression to use for sorting the results. The expression LENGTH(name) calculates the length of the name column for each user, and the DESC keyword sorts the results in descending order based on this calculated value.

Finally, we use the get method to retrieve the sorted results from the database.

This will generate a SQL query that looks something like this:

```
SELECT * FROM users ORDER BY LENGTH(name) DESC
```

This query returns a list of all users, sorted in descending order based on the length of their names.

## Example # 2
Let's assume we have a roles table with the following columns:

```
id | name        | level
---|-------------|------
1  | Admin       | 3
2  | Moderator   | 2
3  | Contributor | 1
```
You want to sort the roles based on their level of importance, rather than their alphabetical order. Here's how we can do that using orderByRaw:

```
$roles = DB::table('roles')
    ->orderByRaw('CASE WHEN level = 3 THEN 1 WHEN level = 2 THEN 2 ELSE 3 END')
    ->get();
```

In this example, you can use the orderByRaw method to specify a raw SQL expression to use for sorting the roles. The expression uses a CASE statement to assign a numerical value to each role based on its level of importance. We assign the value 1 to roles with level 3, 2 to roles with level 2, and 3 to all other roles.

The ORDER BY clause then sorts the roles based on these assigned values, with the roles with the lowest assigned value (i.e., the most important roles) appearing first in the result set.

This will generate a SQL query that looks something like this:

```
SELECT * FROM roles ORDER BY CASE WHEN level = 3 THEN 1 WHEN level = 2 THEN 2 ELSE 3 END
```

This query returns a list of all roles, sorted based on their level of importance.

Example # 3:
Here's an example of a more complex orderByRaw expression in Laravel:

Assume we have a sales table with columns `id, product_id, quantity, price, and created_at`. We want to retrieve a list of the top 10 products by revenue for the current month, and include the total revenue and quantity sold for each product. We can do this using the following query:

```
$topProducts = DB::table('sales')
    ->select('product_id', DB::raw('SUM(quantity) as total_quantity'), DB::raw('SUM(price * quantity) as total_revenue'))
    ->whereBetween('created_at', [Carbon::now()->startOfMonth(), Carbon::now()->endOfMonth()])
    ->groupBy('product_id')
    ->orderByRaw('total_revenue DESC')
    ->take(10)
    ->get();
```


In this example, the select method to select the `product_id`, and calculate the `total_quantity` and `total_revenue `columns using the SUM and DB::raw methods.

We then use the `whereBetween` method to filter the results to only include sales made during the current month.

Next, we use the `groupBy `method to group the results by `product_id`.

We then use the `orderByRaw `method to specify a raw SQL expression to use for sorting the results. The expression `total_revenue `DESC sorts the results in descending order based on the `total_revenue` column that we calculated in the select method.

Finally, we use the take method to limit the results to the top 10 products by revenue, and use the get method to retrieve the results from the database.

This will generate a SQL query that looks something like this:

```
SELECT product_id, SUM(quantity) as total_quantity, SUM(price * quantity) as total_revenue  FROM sales 
WHERE created_at BETWEEN '2023-02-01 00:00:00' AND '2023-02-28 23:59:59' 
GROUP BY product_id 
ORDER BY total_revenue DESC 
LIMIT 10
```
This query returns a list of the top 10 products by revenue for the current month, sorted based on the total revenue generated by each product. Each row in the result set includes the `product_id`, `total_quantity`, and `total_revenue `for the corresponding product.


Note that the expression passed to `orderByRaw` should be a valid SQL expression and properly escaped to avoid SQL injection vulnerabilities. Also, if you need to sort by multiple columns or expressions, you can chain multiple `orderByRaw` calls or use the `orderBy `method instead.