O P
O P

Reputation: 2365

Compare dates in laravel

I have this field $data->created_at and would like to only show data if it's > 30 minutes old

in my view I have:

@if ($data->created_at > strtotime('30 minutes'))
    show data
@endif

This doesn't work. I've also built this statement in the controller, but it doesn't work. It seems to be affected by Carbon in some way.

What's the best way to do this in Laravel?

Upvotes: 1

Views: 3778

Answers (2)

shanecp
shanecp

Reputation: 851

A more 'Laravel way' of doing this would be,

@if($data->created_at > (new \Carbon\Carbon())->subMins(30))
  show data
@endif

Upvotes: 4

Logan Bailey
Logan Bailey

Reputation: 7127

Laravel's created_at and updated_at fields are \DateTime Objects. You should be able to do this using

@if($data->created_at > \new DateTime('-30 minutes'))
    show data
@endif

Upvotes: 2

Related Questions