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

How to use conditional where clause in Laravel 8 eloquent ?

Aman Jain, February 7, 2022October 4, 2022

In Laravel sometimes while creating a eloquent or db builder query you wanted to apply the where 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 check status is given in input then add it in where clause otherwise not .

So here is the syntax of when

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

Example:

$Model->when($role_id==2,function($query){ // if role_id equals to 2 
      return $q->where("status",1);
}, function($query){                    //  if role_id not equals to 2 
      return $q->where("status",2); 
})

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($role_id==2) 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($role_id==2){
   $Model = $Model->where("status",1);
}
else{
   $Model = $Model->where("status",2);
}


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 Aricle table where we wanted to apply were condition on basis of role and then check the status

Example 1 – Laravel conditional where 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()
    { 
        $role_id=2;

        $Article = Article::when($role_id==2,function($query){
                     $query->where("status",2);
                   },function($query){
                     $query->where("status",1);
                   })->get(); 
   }
}

Output will be if role_id is 2 :

select * from `articles` where `status`=2;

Example 2 – Laravel conditional where 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()
    { 
        $role_id=2;

        $Article = new Article;
        if($role_id==2){
          $Article=$Article->where("status",1);
        }
        else{
          $Article=$Article->where("status",2);
        }
         $Article->get()
     
   }
}

Output will be if role_id is 2 :

select * from `articles` where `status`=1;

Also Read : How to use conditional validation Laravel 8 ?

Related

Php Laravel conditionallaravelwhere

Post navigation

Previous post
Next post

Related Posts

Php Creating resource controller in laravel

How to create resource controller in Laravel 8 ?

November 7, 2021November 7, 2021

Resource controller is helpful when you want Create, Read, Update and Delete (CRUD) operations. If you have a model with same set of actions like crud then resource controller are useful. we can create resource controller easily using the artisan command. Above command will generate controller ImageController in \app\Http\Controllers. As…

Read More
Php How to Call a POST Rest Api in Laravel

How to Call a POST Rest Api in Laravel ?

June 7, 2022June 7, 2022

In this article we will learn to call an post rest api in Laravel. Whenever we want to access the third party data we need to access the data using the APIs, we send a request to another server means outside our application and they respond with preformatted structure. Post…

Read More
Php How to print raw sql query in eloquent laravel

How to print raw sql query in eloquent laravel ?

November 23, 2022March 16, 2024

In this article we will learn to print raw sql query in eloquent laravel. Sometime to debug the MySQL query in laravel eloquent we need to echo raw sql query and want to know exact query. In laravel we have multiple methods to print database query in laravel 8 and…

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

  • 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

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version