Laravel blade compare two date

2019-05-14 20:24发布

问题:

I would like to compare 2 dates. So I create a condition like this in my template blade:

@if(\Carbon\Carbon::parse($contrat->date_facturation)->format('d/m/Y') < $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

My variable $dateNow has the same format on my value in $contract->date_facturation

Screenshot

It add a red background on the date 25/02/2018 while the date is not less than the variable $contract->date_facturation

Do you have any idea of ​​the problem?

Thank you

回答1:

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.



回答2:

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.



回答3:

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



标签: laravel blade