How to parse Carbon dates with useful macro in Laravel

Categorized as Laravel Tagged ,

When you try to parse a date with Carbon, by default it will throw an exception when parsing an invalid date format. So you need to manually try/catch the exception in your code.

But sometimes, you might need a false value rather than dealing with the exception. So here is the macro that will help you achieve that.

In the AppServiceProvider.php:

use Illuminate\Support\Carbon;

public function boot(): void
{
  // default: en
  Carbon::macro('parseOrFalse', function ($string) {
    return rescue(fn() => Carbon::parse($string), false, false);
  });

  // or chain with multiple locale
  Carbon::macro('parseOrFalse', function ($string) {
    return rescue(fn() => Carbon::parse($string), false, false) 
    ?: rescue(fn() => Carbon::parseFromLocale($string, 'id'), false, false);
  }); 

}

Somewhere else:

use Illuminate\Support\Carbon;

$date = Carbon::parseOrFalse('invalid date'); // false
$date = Carbon::parseOrFalse('today'); // carbon instance

$today = Carbon::parseOrFalse('not today') ?: today(); // Carbon instance

if ($date = Carbon::parseOrFalse($request->from)) {
  $query->whereDate('created_at', '>=', $date);
}

Leave a reply

Your email address will not be published. Required fields are marked *