Home > Software design >  Laravel wheredate between two dates with different month, return data that not in the date range
Laravel wheredate between two dates with different month, return data that not in the date range

Time:12-04

I use whereDate to get data that are in range of given date

$data = Work::where([
        ['employeeID', '=', $employee],
    ])->whereDate('date', '>=', $from)
    ->whereDate('date', '<=', $to)->get();
    return $data;

Data range

$from = 16-05-2021
$to = 30-05-2021

But it also returns data that not in the date range

{"0":{"id":421,"employeeID":(classified),"jobID":(classified),"date":"31-05-2021","workTime":4,"created_at":"2021-12-01T03:13:04.000000Z","updated_at":"2021-12-01T03:13:04.000000Z"},
"4":{"id":425,"employeeID":(classified),"jobID":(classified),"date":"11-06-2021","workTime":6,"created_at":"2021-12-01T03:13:04.000000Z","updated_at":"2021-12-01T03:13:04.000000Z"},
"6":{"id":427,"employeeID":(classified),"jobID":(classified),"date":"14-06-2021","workTime":6,"created_at":"2021-12-01T03:13:04.000000Z","updated_at":"2021-12-01T03:13:04.000000Z"},
"7":{"id":428,"employeeID":(classified),"jobID":(classified),"date":"20-05-2021","workTime":10,"created_at":"2021-12-01T03:13:04.000000Z","updated_at":"2021-12-01T03:13:04.000000Z"},
"9":{"id":430,"employeeID":(classified),"jobID":(classified),"date":"15-06-2021","workTime":10,"created_at":"2021-12-01T03:13:04.000000Z","updated_at":"2021-12-01T03:13:04.000000Z"},
"10":{"id":431,"employeeID":(classified),"jobID":(classified),"date":"25-05-2021","workTime":10,"created_at":"2021-12-01T03:13:04.000000Z","updated_at":"2021-12-01T03:13:04.000000Z"},
"24":{"id":445,"employeeID":(classified),"jobID":(classified),"date":"22-05-2021","workTime":10,"created_at":"2021-12-01T03:13:05.000000Z","updated_at":"2021-12-01T03:13:05.000000Z"}}

it also return data from month 6 when the date range are 16-05-2021 and 30-05-2021

CodePudding user response:

You should convert your date using Carbon so you can use whereDate clause:

->whereDate('date', '>=', \Carbon\Carbon::parse($from)->format('d-m-Y'))

CodePudding user response:

You could use whereBetween()

Work::where([
        ['employeeID', '=', $employee],
    ])->whereBetween('date', [$from, $to])
->get();

Don't forget to properly format a date.

use Carbon\Carbon;

$from = Carbon::parse($from)->format('d-m-Y');
// and $to
  • Related