How to Write Conditional Queries in Laravel
I will show you how to write conditional queries in Laravel with perfect example Advanced Where.
Advanced where clauses
$result = DB::table('table_name')
->where(function($query) use ($var1, $var2, $var3, $var4) {
if($var1) {
$query->where('column_name', $var1);
}
if($var2){
$query->where('column_name', $var2);
}
if($va3){
$query->where('column_name', $va3);
}
if($var3){
$query->where('column_name', $var3);
}
})
->get();
Splitting the whole query
$query = DB::table('table_name');
if($var1) {
$query->where('column_name', $var1);
}
if($var2) {
$query->where('column_name', $var2);
}
if($var3) {
$query->where('column_name', $var3);
}
if($offset && $limit) {
$query->skip($offset)->take($limit);
}
$result = $query->get();