zwl1619
zwl1619

Reputation: 4232

Laravel 5.2 : How to write this `if` statement about label?

I want to show the label "New" beside the article that it's update time is no more than 3 days. Some help please,thanks in advance.

How to write the if statement below?

@foreach ($articles as $article)
    <a href="#">{{$article->title}}</a>
    @if($article->updated_at)     //How to write here?
        <span class="label label-danger">New</span>
    @endif
@endforeach

Upvotes: 0

Views: 41

Answers (1)

codisfy
codisfy

Reputation: 2183

You can do it like this:

In your Articles Model ensure that the updated_at becomes Carbon instance which you can do by adding a property in your model like :

protected $dates = ['updated_at']; 

Also in the model define a method which will check if the article is latest :

public function isLatest() {
    return $this->updated_at->diffInDays(\Carbon\Carbon::now()) <= 3;
}

The method is basically checking if the diff in days is less than or equal to 3 as mentioned by you.

Now in your view, use the method on the $article object like :

 @if ($article->isLatest()) 
     <!-- when true --> 
 @else
    <!-- when false -->
 @endif

I hope it helps

Upvotes: 1

Related Questions