Carbon (laravel) deal with invalid date

Pass Laravel's validation before use it. Create a validator like this:

     protected function validator(array $data)
{
    //$data would be an associative array like ['date_value' => '15.15.2015']
    $message = [
        'date_value.date' => 'invalid date, enduser understands the error message'
    ];
    return Validator::make($data, [
        'date_value' => 'date',
    ],$message);
}

And call him right before use your date:

$this->validator(['date_value' => $date])->validate();
// $this->validator(request()->all())->validate(); you can pass the whole request if fields names are the same

Carbon::parse($date);

You can add all your desired fields to validator and apply multiple validations handling every message or using the default message. This would be the way if you are validating User's input


You can catch the exception raised by Carbon like this:

try {
    Carbon::parse($date);
} catch (\Exception $e) {
    echo 'invalid date, enduser understands the error message';
}

Later edit: Starting with Carbon version 2.34.0, which was released on May 13, 2020, a new type of exception is being thrown: Carbon\Exceptions\InvalidFormatException

So if you're using a newer version of Carbon, you can actually do this more elegantly

try {
    Carbon::parse($date);
} catch (\Carbon\Exceptions\InvalidFormatException $e) {
    echo 'invalid date, enduser understands the error message';
}

Thank you Christhofer Natalius for pointing this out!