How to Use Conditional Statements in Laravel 9 Query Builder?

Laravel query builder is a very good tool out of the box in Laravel 9 to get and manipulate database. It doesn’t care about anything we are using like SQL, sqlLite or mongodb.

The variable we are passing here will controller execution of inside function. In when() method if $flag is true then inner function query will be applied. Otherwise it will be ignored.

$flag = true;
$leads  = DB::table( 'leads' )->when( $flag, function ( $query ) {
	$query->whereIn( 'age', [ 20, 24 ] );
} )->get();

unless() method is quite opposite. If $flag is true the inner function query will be ignored but if its false then it will be executed.

$flag = false;
$leads  = DB::table( 'leads' )->unless( $flag, function ( $query ) {
	$query->whereIn( 'age', [ 20, 24 ] );
} )->get();

I hope now you understand everything about query builder. If you have any problems please write comments, we really appreciate that.