Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel blade compare two date

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

like image 815
Christopher Avatar asked Dec 18 '22 09:12

Christopher


1 Answers

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.

like image 58
Elias Soares Avatar answered Jan 05 '23 14:01

Elias Soares