zwl1619 zwl1619 - 1 year ago 60
PHP Question

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

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>

Answer Source

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 --> 
    <!-- when false -->

I hope it helps