phplaraveldatepickerphp-carbondate-parsing

Laravel Datepicker Failed to parse time string


I'm trying to build a query in Laravel using whereBetween and I have a problem with the dates-range. I'm using Carbon to get the inputs, looking like this:

$dateRange = Carbon::parse($request->get('anniversary'));

I received the following error on submit:

DateTime::__construct(): Failed to parse time string (06/01/2019 - 06/30/2019) at position 11 (-): Unexpected character

Then, I changed the $dateRange in this form:

$dateRange = Carbon::parse(str_replace('-', '', $request->get('anniversary')));

After that, this error occured:

DateTime::__construct(): Failed to parse time string (06/01/2019 06/30/2019) at position 12 (0): Double date specification

The whereBetween clause looks like this:

->whereBetween('anniversary', [$dateRange])

Any ideas on how can I fix this?


Solution

  • You need to explode the retrieved Datepicker to two values. (Start Date and End Date)

    $dateArray = explode('-', $request->get('anniversary'));
    
    $startDate = $dateArray[0];
    $endDate = $dateArray[1];
    

    Now you can use

    ->whereBetween('anniversary', $dateArray);