DEV Community

Cover image for Carbon PHP Quick Tip
Sean Kegel
Sean Kegel

Posted on • Edited on • Originally published at seankegel.com

Carbon PHP Quick Tip

Using Carbon::make

Recently, I was working on handling API responses and I wanted to pass them into 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,
   ...
);
Enter fullscreen mode Exit fullscreen mode

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 can use Carbon::make. It returns null if the value passed in is null.

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

Top comments (0)