Laravel orderByRaw() Query Example

Laravel orderByRaw() Query Example

Hello friends, Today you will learn Laravel orderByRaw() Query Example. In this post we provide example of laravel orderbyraw example. How to use orderByRaw with joined table data. in laravel You can understand a concept of laravel first name and last name order by example.

You can use the laravel 8 orderByRaw eloquent method to building query in laravel apps. And also use laravel select raw with multiple conditions in eloquent queries.

So, let’s see following examples that will help you how to use orderByRaw() eloquent query in laravel:

  1. Example 1: Laravel OrderByRaw Query using Model
  2. Example 2: orderByRaw Query using Query Builder
  3. Example 3: Laravel orderByDesc() Example
Read Also :  How to Flash Message in Laravel Example

Example 1: Laravel OrderByRaw Query using Model

<?php
   
namespace App\Http\Controllers;
   
use Illuminate\Http\Request;
use App\User;
   
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::select("*")
                        ->where("status", 1)
                        ->orderByRaw("concat(first_name, ' ', last_name)")
                        ->get();
   
        dd($users);
    }
}

Example 2: orderByRaw Query using Query Builder

<?php
   
namespace App\Http\Controllers;
   
use Illuminate\Http\Request;
use App\User;
   
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = DB::table('users')->select("*")
                        ->where("status", 1)
                        ->orderByRaw("concat(first_name, ' ', last_name) DESC")
                        ->get();
   
        dd($users);
    }
}

Example 3: Laravel orderByDesc() Example