0

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.

1 Answer 1

2

It is because you don't set month if it's not there but it should work as the conditions are the same. Wouldn't simplifying it help, doing it all in one statement, instead of setting it beforehand. Then you don't have the problem of having instantiated the property.

->when(request()->filled('month'), function ($q) {
    return $q->whereMonth('date', sprintf("%02d",request()->month));
})
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, looks like that fixed it, my syntax was off. I was planning on inlining it once I got a working solution, just wanted to make it clear what exactly I was trying to do.
Glad that it helped. You code was on point, thought maybe a bug between revisions or something, just unnecessary to only set it when present when you just can do it in the condition :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.