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

Snowfox1991's avatar

Improve the search by specific date in Laravel

I have the information of events in database which have (events title, from_date, to_date)

events from_date to_date events 1 2018-10-12 2018-10-16 events 2 2018-10-15 2018-10-19 events 3 2018-10-11 2018-10-17 And this is my search by specific date function

$from_date = Carbon::parse(request('from_date'))->endOfDay();

    $events = Events::where('from_date', '<=' ,$from_date)
        ->where('to_date', '>=' ,$from_date)
    ->get();


    return $events;

My route for this API is day-search. so when i input api/day-search?from_date=my input. When i input the 2018-10-15, it should be shown all 3 events occur during the 2018-10-15.

Is there anyway to improve the accuracy of this code? Thank you.

0 likes
3 replies
burlresearch's avatar
Level 40

You could do this in a single call:

$from_date = Carbon::parse(request('from_date'));

Events::whereBetween('from_date', [$from_date->startOfDay(),$from_date->endOfDay()])->get();

I don't think this changes the accuracy, but it might do what you want...

Snowfox1991's avatar

Maybe this is what i want. I forgot to check the startOfDay and endOfDay. Thanks for reminding me about this.

Cronix's avatar

If you're getting between start of today and end of today, then that's just "today" as the time doesn't matter. It's just the date.

$from_date = Carbon::parse(request('from_date'));

Events::whereDate('from_date', $from_date->toDateString())->get();
// same as using between $from_date->startOfDay() and $from_date->endOfDay()
1 like

Please or to participate in this conversation.