Laravel blade compare two date

醉酒当歌 提交于 2019-12-04 12:15:05

The problem is that you are trying to compare two date strings. PHP don't know how to compare date strings.

Carbon::format() returns a string. You shoud convert your dates to a Carbon object (using parse) and use Carbon's comparison methods, as described on Carbon Docs (Comparison).

For your example, you should do:

// Note that for this work, $dateNow MUST be a carbon instance.
@if(\Carbon\Carbon::parse($contrat->date_facturation)->lt($dateNow))
    <td class="danger">
        {{ \Carbon\Carbon::parse($contrat->date_facturation)->format('d/m/Y') }}
    </td>
@else
    <td>
        {{ \Carbon\Carbon::parse($contrat->date_facturation)->format('d/m/Y') }}
    </td>
@endif

Also your code looks repetitive, and assuming that $dateNow is a variable with current date, you can use Carbon::isPast() method, so rewriting your code, it becomes:

<?php
    $date_facturation = \Carbon\Carbon::parse($contrat->date_facturation);
?>
@if ($date_facturation->isPast())
    <td class="danger">
@else
    <td>
@endif
        {{ $date_facturation->format('d/m/Y') }}
    </td>

This makes your code less repetitive and faster, since you parse the date once, instead of twice.

Also if you want your code better, use Eloquent's Date Mutators, so you won't need to parse dates everytime that you need on your views.

You can parse both dates, change your code to:

<td class="{{ Carbon\Carbon::parse($contrat->date_facturation) < Carbon\Carbon::parse($dateNow) ? 'danger' : '' }}">
    {{ \Carbon\Carbon::parse($contrat->date_facturation)->format('d/m/Y') }}
</td>

Alternatively, you can use the date mutators. In this case you'll not need to parse dates.

Compare date in blade template

I used this method of Carbon:

@foreach($earnings as $data)

@if($data->created_at ==  Carbon\Carbon::today())
      <tr class="alert alert-success">
@else
      <tr>
@endif
  ....
@endforeach

More Details

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!