Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jmadlena's avatar

Only return value if not null in model accessor

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!

0 likes
5 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Try

return Attribute::make(
            get: fn ($value) => is_null($value) ? null : Carbon::createFromTimestamp($value) 
        ); 
1 like
jmadlena's avatar

@Sinnbeck Thanks! I happened to find a similar solution as well. Marked yours as the best answer since you were first.

cwhite's avatar

Something like this?

protected function collectionResumesAt(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => $value
                ? Carbon::createFromTimestamp($value)
				: null,
        );
    }

Or this might work (from @sinnbeck's comment, have to negate the null value first):

return Attribute::make(
    get: fn ($value) => ! $value ?: Carbon::createFromTimestamp($value),
); 
1 like
jmadlena's avatar

@cwhite Thanks! Happened to stumble on this myself right after posting. Thanks so much for your reply and help.

jmadlena's avatar

Of course, moments after posting this I stumbled across the solution. In this case you need to use the ternary operator instead of a null coalescing operator. Probably obvious to many, but I haven't used either of these much.

Here's my new code and it works like a charm:

protected function collectionResumesAt(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => ($value) ? Carbon::createFromTimestamp($value) : null,
        );
    }

Hope this helps someone else!

Please or to participate in this conversation.