Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

chrisgrim's avatar

How to use a where() inside a when() correctly to get dates

Hi All, I am trying to return events that are within the last 30 days. I am using the code

public function fetch(Request $request)
    {
        return Event::whereIn('status',['p', 'e'])
            ->with('user','clicks','category', 'location', 'remotelocations', 'organizer', 'shows', 'curatedCheck')
            ->when(request('date') === 'published', function ($q) {
                $q->orderByDesc('published_at');
            })
            ->when(request('date') === 'updated', function ($q) {
                $q->orderByDesc('updated_at');
            })
            ->when(request('date') === 'twoweeks', function ($q) {
                $q->where(
                    'closingDate','>=', Carbon::now()->subDays(30)->toDateTimeString()
                );
            })
            ->paginate(15);
    }

However when I make request(date) = to twoweeks nothing is filtered. I am loading Carbon into my controller.

0 likes
7 replies
tykus's avatar

Are you sure that check is passing; does this expression request('date') === 'twoweeks' evaluate true?

Also, if you are filtering by a date; then whereDate is probably more appropriate

$q->whereDate('closingDate', '>=', today()->subDays(30));
chrisgrim's avatar

@tykus Yeah If I try something like

->when(request('date') === 'twoweeks', function ($q) {
                $q->whereDate(
                    'id','=', 14
                );
            })

it will just return the one model

chrisgrim's avatar

@tykus I think I was confusing myself actually. I am just trying to get any event that has a closingDate in the next 30 days. Carbon::now()->subDays(30) is wrong

chrisgrim's avatar

I am so sorry to waste your time. I tried 'closingDate','<', today()->addDays(14) and that seems to be working,

Please or to participate in this conversation.