I am trying to create a query based on data sent from a POST request. I got it working when I expect both values in my form to be set, however I would like one of the values to be optional.
In my Controller if I make that call
$year = request()->year;
if(request()->filled('month')){
$month = sprintf("%02d",request()->month);
}
That works for correctly setting $year and $month, but I run in to issues in my query. This is what my query looks like:
$matches = DB::table('games')
->join('clubs', 'games.opposition','=','clubs.id')
->join('stadiums', 'games.stadium','=','stadiums.id')
->select('date','clubs.name AS opposition','games.home/away','stadiums.name')
->whereYear('date',$year)
->whereMonth('date',$month)
->get();
I want that ->whereMonth statement to only be added if the month value is set in the form, so I tried to surround it with
->when(request()->filled('month'),function ($q) use ($month) {
return $q->whereMonth('date',$month);
})
But it's giving me a Undefined variable: month error.
Does anyone have any suggestions? I tried to replace request()->filled('month) with just $month but it gave me the same error.