I was trying to write an eloquent query that fetches results based on the date. But the date will be given separately as year, month and day. I wanted the query to work when I also pass 'all' for one or more of the inputs (like for all days in a month if the day is given as 'all'). I know I can do it using different 'if' combinations, but I wanted to have some easy way to do it. Is there any way?
Here is the code I have written.
$year = $request->input('year');
$month = $request->input('month');
$day = $request->input('day');
$reports = DailyReport::whereYear('date', $year)
->whereMonth('date', $month)
->whereDay('date', $day)->get();
CodePudding user response:
Try it out this
$reports = DailyReport::when($request->has('year'), function($query) use ($request){
$request->whereYear('date', $request->year)
})
->when($request->has('month'), function($query) use ($request){
$request->whereMonth('date', $request->month)
})
->when($request->has('day'), function($query) use ($request){
$request->whereDay('date', $request->day)
})->get();
CodePudding user response:
This worked finally, after looking all the helpful answers of course.
$year = $request->input('year');
$month = $request->input('month');
$day = $request->input('day');
$reports = DailyReport::when($year!='all', function ($query) use($year) {
return $query->whereYear('date', $year);
})
->when($month!='all', function ($query) use($month) {
return $query->whereMonth('date', $month);
})
->when($day!='all', function ($query) use($day) {
return $query->whereDay('date', $day);
})->get();