How To Use Order By Statement With Example In Laravel

admin_img Posted By Bajarangi soft , Posted On 23-09-2020

Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems. The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.

How to Use Order By statement in Laravel

Syntax for SQL ORDER BY Keyword.

SELECT column_name list
FROM table_name
ORDER BY column1, column2, ... ASC|DESC

To learn more about SQL, please visit our BajarangiSoft site.

 

How can you use Order By statement in laravel

The orderBy method allows you to sort the result of the query by a given column. The first argument to the orderBy method should be the column you wish to sort by, while the second argument controls the direction of the sort and may be either asc or desc:

Example(1)
​​<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;//include this

class UserController extends Controller
{
    public function index()
    {
        $users = DB::table('users')->orderBy('name', 'desc')->get();
        return view('user.index', ['users' => $users]);
    }
}
?>

above example order by the name in descending order and return from controller to user index.blade.php page

Related Post