mongodb / laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)
https://www.mongodb.com/docs/drivers/php/laravel-mongodb/
MIT License
7.02k stars 1.43k forks source link

Can't filter by date #2529

Closed frenchqwerty closed 1 year ago

frenchqwerty commented 1 year ago

Description:

I have a date array and I want to retrieve those that are an interval.

For example: Retrieve me those with a date between 2023-03-01 and 2023-03-31

Steps to reproduce

My collection is presented :

"departures": [
            "2022-10-23T23:30:00.000+00:00", // Date object
                         "2023-02-02T23:30:00.000+00:00",
                         "2023-11-10T18:00:00.000+00:00"
        ],
        "price": 310,
$beginDate = Carbon::createFromFormat("Y-m-d", "2023-03-01");
$endDate = clone $beginDate;
$endDate->endOfMonth();

$search->whereBetween('departures', [$beginDate->toDateTime(), $endDate->toDateTime()])->get()->toArray();

Expected behaviour

It must return me an empty array.

Actual behaviour

It returns me all the table.

puuble commented 1 year ago

Hi you can use

protected $dates = ['startDate', 'endDate']; //<- this text should be add in model

$d = WorkPeriod::where('startDate', '>=', Carbon::parseFromLocale($this->start))->where('endDate','<=',Carbon::parseFromLocale($this->end));

$this->start = can be string no problem with parseFromLocale also you can use whereDate()

GromNaN commented 1 year ago

Thanks @puuble for the correct answer. $dates is now replaced by $casts.