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

l_stankov01's avatar

Laravel Trying to get property of non-object of date! HELP

Hello i have this code

$lastPurchaseDate = Auth::user()->orders->last()->created_at->toFormattedDateString()->isEmpty() ? $lastPurchaseDate = 'None' : $lastPurchaseDate = Auth::user()->orders->last()->created_at->toFormattedDateString();

But this return again "Trying to get property of non-object". Please help me. Thanks!

0 likes
6 replies
Vilfago's avatar

If you try an "if" statement, try this :

$lastPurchaseDate = (Auth::user()->orders->last()->created_at->toFormattedDateString()->isEmpty()) ?  'None' : Auth::user()->orders->last()->created_at->toFormattedDateString();

or

if(Auth::user()->orders->last()->created_at->toFormattedDateString()->isEmpty())
{
$lastPurchaseDate = 'None';
 }else{
$lastPurchaseDate = Auth::user()->orders->last()->created_at->toFormattedDateString();
}

Both are the same.

Vilfago's avatar

What do you get when var_dump:

Auth::user()->orders->last();

?

l_stankov01's avatar

@Vilfago It doesnt return anything couse this is a new user and dont have any orders. This happen only when new user registered !

Vilfago's avatar
Vilfago
Best Answer
Level 20

You ask for created_at of an object which does not exist as you said.

Let's try

$lastPurchaseDate = (Auth::user()->orders->last()) ?  'None' : Auth::user()->orders->last()->created_at->toFormattedDateString();

l_stankov01's avatar

@Vilfago i fixed it with this

(empty(Auth::user()->orders->last())) ?  'None' : Auth::user()->orders->last()->created_at->toFormattedDateString();

Thanks.

Please or to participate in this conversation.