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 ?