Try
return Attribute::make(
get: fn ($value) => is_null($value) ? null : Carbon::createFromTimestamp($value)
);
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have a model in my API that stores a unixtime stamp supplied by the Stripe API. I'd like to store this value in its native format, but return a Datetime object to my app on read.
I have set up an accessor to do just that, however Carbon returns a value of 12/31/1969 when the value is null. I'd like to return null if the DB value is null, and a Carbon Datetime object if not. Here's my code:
protected function collectionResumesAt(): Attribute
{
return Attribute::make(
get: fn ($value) => Carbon::createFromTimestamp($value),
);
}
I've tried to use a null coalescing operator, but it looks like it won't work because it's in an arrow function.
Any ideas on how to return null if the model value is null, and only return the Carbon datetime object if there's a value?
I'm probably missing something simple, but I'm unfamiliar with Laravel's new accessor API.
Any help would be appreciated!
Try
return Attribute::make(
get: fn ($value) => is_null($value) ? null : Carbon::createFromTimestamp($value)
);
Please or to participate in this conversation.