Carbon PHP Quick Tip

Carbon PHP Quick Tip

·

1 min read

Using Carbon::make

Recently, I was working on handling API responses and I wanted to pass them to a DTO. One of the fields was an optional deleted_at column. In my DTO, I wanted that to be converted to a Carbon datetime object.

Carbon comes packaged with Laravel, but can also be used standalone for other PHP packages and adds excellent extensions to the PHP datetime object.

To build the DTO, my first go at it was to have something like below:

new DataDto(
   ...
   deleted_at: isset($data['deleted_at']) ? Carbon::parse($data['deleted_at']) : null,
   ...
);

I needed to first check if $data['deleted_at'] is not null, otherwise, Carbon::parse would return a new Carbon instance with the current date and time.

The above code works fine but it is kind of hard to look at, especially with the full object instantiation. So instead, I found I could use Carbon::make. It returns null if the value passed in is null.

new DataDto(
   ...
   deleted_at: Carbon::make($data['deleted_at']),
   ...
);