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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With