Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
How to use conditional orderby in Laravel 8

How to use conditional orderBy clause in Laravel 8 eloquent ?

Aman Jain, February 12, 2022October 4, 2022

In Laravel sometimes while creating a eloquent or db builder query you wanted to apply the orderBy clause on basis of some conditions and to achieve it you may use if else condition but laravel 8 itself provides solution to handle such type of situations using when method.

Laravel eloquent when method accepts three parameter first parameter is boolean, second is anonymous function and third is also a function means if first parameter is true then it will call the second parameter function and if first parameter is false then it will execute the third parameter.

In this tutorial we will take a simple example of articles to sort by title and created date, if user select sort by title then apply orderBy title column otherwise default created at column .

So here is the syntax of when

$Model->when(boolean, Function, Function);

Example:

$Model->when($sortBy=='title',function($query){ // if sortBy equals to title 
      return $q->orderBy("title");
}, function($query){                    //  if sortBy not equals to title 
      return $q->orderBy("created_at","DESC"); 
})

In the above example as you can se we created a model and then used when method to execute the if else in laravel way. we passed three parameters to when method first is boolean($sortBy=='title') and two consecutive functions for true and false.

We can also make where query conditional in traditional way using if and else statement as below

Example:

if($sortBy=='title'){
   $Model = $Model->orderBy("title");
}
else{
   $Model = $Model->where("title",'DESC');
}


Sometime we need to check multiple condition or some logic to add the where thus in that case we can use multiple when or if else condition validations in laravel.

Let’s take an example of Article table where we wanted to apply orderBy condition on basis of sortBy user input and then show the records

Example 1 – Laravel conditional orderBy using when

So in this example i will use laravel query builder or eloquent when method to apply if else .

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\User;
  
class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    { 
        $sortBy=$request->get("sortBy");

        $Article = Article::when($sortBy=='title',function($query){
                     $query->orderBy("title");
                   },function($query){
                     $query->orderBy("created_at",'DESC');
                   })->get(); 
   }
}

Output will be if sortBy is title :

select * from `articles` where order by title

Example 2 – Laravel conditional order by using if else

So in this example i will use laravel query builder or eloquent if else to build conditional query .

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\User;
  
class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    { 
         $sortBy=$request->get("sortBy");

        $Article = new Article;
        if($sortBy=='title'){
          $Article=$Article->orderBy("title");
        }
        else if($sortBy=='status'){
          $Article=$Article->orderBy("status");
        }
        else{
          $Article=$Article->where("created_at",'DESC');
        }
         $Article->get();
     
   }
}

Output will be if sortBy is title :

select * from `articles` order by title
# OR
select * from `articles` order by created_at desc

Also Read : How to use conditional where clause in Laravel 8 eloquent ?

Related

Php Laravel conditionallaravelwhere

Post navigation

Previous post
Next post

Related Posts

Php Laravel group by with example

How to use laravel group by with example ?

January 22, 2022January 22, 2022

MySQL group by is used to group same column value multiple rows into one row so to create the group by query we used groupBy method. laravel groupBy method accepts single and multiple parameter as column name. In this article i will show you to use groupBy in multiple ways,…

Read More
Php How to Filter Data Using Relational Model in Laravel

How to Filter Data Using Relational Model in Laravel ?

June 29, 2022July 1, 2022

In this article i will show you to filter data using the relational model in laravel. Using the laravel relationship between the models we can easily fetch relative data but sometimes we want to fetch the data by filtering the child model that affect the result of parent model. You…

Read More
Php Laravel sum in eloquent query

Laravel sum in eloquent query with example

January 23, 2022November 10, 2023

In this article we will learn to use aggregate function sum in laravel eloquent and query builder. Laravel itself provide inbuilt method to sum the columns like in MySQL or SQL based database we can do sum of columns using sum aggregate function. Sum method will give you the sum…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
  • Understanding High Vulnerabilities: A Deep Dive into the Weekly Summary
  • Building a Million-Dollar Brand: The Journey of Justin Jackson
  • Mastering Schedule Management with Laravel Zap
  • The Resilience of Nature: How Forests Recover After Fires
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version