php - DateTime::__construct(): Failed to parse time string (from) at position 0 (f): The timezone could not be found in the database

I am getting this error

DateTime::__construct(): Failed to parse time string (from) at position 0 (f): The timezone could not be found in the database

I tried to different methods to solve this error. but not successfully at all.

$from = null;
$to = null;

try{
    if ($request->input('from') || $request->input('to')) {

        if ($request->input('from')) {
            $from = Carbon::createFromFormat('Y-m-d', $request->input('from'))->toDateString();
        }
        if ($request->input('to')) {
            $to = Carbon::createFromFormat('Y-m-d', $request->input('to'))->toDateString();
        }

        $validator = Validator::make(
            [
                'from' => $from,
                'to'   => $to
            ],
            [
                'from' => 'required|date|date_format:Y-m-d',
                'to'   => 'required|date|date_format:Y-m-d|after_or_equal:from',
            ]
        );
        if ($validator->fails()) {
            return \Redirect::back()
                ->with(array('flash_message' => "Please Enter Correct Date Format"));
        }
    }
} catch (\Exception $e)
{
    \Log::debug("Time invalid ");
}

issue is fire in here i think $validator->fails()

anyone have an idea about this?

Answer

Solution:

        // Validate that the strings have a date format
        $validator = Validator::make(
            $request->all(),
            [
                'from' => 'required|date|date_format:Y-m-d',
                'to'   => 'required|date|date_format:Y-m-d|after_or_equal:from',
            ]
        );

        if ($validator->fails()) {
            return \Redirect::back()
                ->with(array('flash_message' => "Please Enter Correct Date Format"));
        }

        // Then after validation, use the string to create date objects
        $from = Carbon::createFromFormat('Y-m-d', $request->input('from'));
        $to = Carbon::createFromFormat('Y-m-d', $request->input('to'));

Source