You can use when
$query->when(!in_array('All',$region->toArray()), function ($q) {
$q->whereIn('store_region',$region);
})->latest()->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I want to retrieve data based on certain condition. The condition is I need check first it matches the brands names and then I need to check the regions. If region is equal to All then no need to check for regions and it is not then I need to check regions as well.
I have tried some code But it is not working. I need some help in writing a Laravel query.
public function index(Request $request)
{
$brand_name = Auth::user()->brands()->get(['brand_name']);
$brands = Brands::whereIn('brand_name',$brand_name)->get(['id']);
$region = Auth::user()->regions()->get(['region_name']);
$claim = Claim::whereIn('brand_id',$brands)
->where(function($query) use($region) {
if(!in_array('All',$region->toArray()))
{
$query->whereIn('store_region',$region);
}
})->latest()->get();
dd($claim);
}
I don't know whether we can use if condition inside query or not. I have tried like this but not working
$claim = Claim::whereIn('brand_id',$brands)
->when(!in_array('All',$region->flatten()->toArray()),function($q){
$q->whereIn('store_region',$region);
})->latest()->get();
Please or to participate in this conversation.