php - Multiple conditional clause filter in Laravel
![](/images/info.png)
I'm trying to filter a table, but some request values can be null. Is there a way to make it more simple, or do I need to create multiple IF statements?
$archives = Archive::when($vehicle, function ($query) use ($vehicle) {
return $query->where('vehicle_id', $vehicle);
})->when($month, function ($query) use ($month) {
return $query->whereMonth('startduration', $month)
->orWhereMonth('endduration', $month);
})->when($year, function ($query) use ($year) {
return $query->whereYear('startduration', $year)
->orWhereYear('endduration', $year);
})->when($status, function ($query) use ($status) {
return $query->where('archivedtype', $status);
})->orderBy('endduration', 'desc')->paginate(20);
Answer
Solution:
Solved it. Thanks
$archives = Archive::where( function($query) use($request){
return $request->vehicle ? $query->where('vehicle_id',$request->vehicle) : '';
})
->where(function($query) use($request){
return $request->month ? $query->whereMonth('startduration',$request->month)->orWhereMonth('endduration',$request->month) : '';
})
->where(function($query) use($request){
return $request->year ? $query->whereYear('startduration',$request->year)->orWhereYear('endduration',$request->year) : '';
})
->where( function($query) use($request){
return $request->status ? $query->where('archivedtype',$request->status) : '';
})
->get();
Answer
Solution:
$archives = Archive::query()
->when($request->month, function ($query, $m) {
$query->where(fn ($q) => $q->whereMonth('startduration', $m)->orWhereMonth('endduration', $m));
})
->when($request->year, function ($query, $y) {
$query->where(fn ($q) => $q->whereYear('startduration', $y)->orWhereYear('endduration', $y))
})
->when($request->vehicle, fn ($q, $v) => $q->where('vehicle_id', $v))
->when($request->status, fn ($q, $s) => $q->where('archivedtype', $s))
->orderBy('endduration', 'desc')
->paginate(20);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: gd library extension not available with this php installation.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.