Tomoro
Tomoro

Reputation: 1

How to make condition check data sent on time or not in Laravel

I have tried to make it but it's not working.

My code:

@if (Carbon\Carbon::parse($tugas->created_at)->toDateString() < Carbon\Carbon::parse($sub->deadline)->toDateString())
    @if (Carbon\Carbon::parse($tugas->created_at)->toTimeString() < Carbon\Carbon::parse($sub->deadline)->toTimeString())
        <td class="table-success">On time</td>
    @else
        <td class="table-danger">late</td>
    @endif
@else
    <td class="table-danger">late</td>
@endif

Upvotes: 0

Views: 575

Answers (3)

shaedrich
shaedrich

Reputation: 5735

By default, created_at should already been cast to Carbon so I recommend doing the same with deadline.

class Sub extends Model
{
    protected $casts = [
        'deadline' => 'datetime'
    ];
}

You can't really compare date strings. They have to be Carbon objects. Carbon offers methods for comparison:

@if ($tugas->created_at->isBefore($sub->deadline))
    @if (Carbon\Carbon::parse($tugas->created_at)->toTimeString() < Carbon\Carbon::parse($sub->deadline)->toTimeString())
        <td class="table-success">On time</td>
    @else
        <td class="table-danger">late</td>
    @endif
@else
    <td class="table-danger">late</td>
@endif

I guess, the second comparison is now somewhat obsolete so it can be shortened to this:

@if ($tugas->created_at->isBefore($sub->deadline))
    <td class="table-success">On time</td>
@else
    <td class="table-danger">late</td>
@endif

Upvotes: 0

weiwait
weiwait

Reputation: 1

Carbon::now()->lessThan(Carbon::now()->subMinute()) // false

This is date comparison

Upvotes: 0

KyleK
KyleK

Reputation: 5056

Date instance (and so Carbon instance too) can be compared without being converted into strings:

@if (new \Carbon\Carbon($tugas->created_at) < new \Carbon\Carbon($sub->deadline))
    <td class="table-success">On time</td>
@else
    <td class="table-danger">late</td>
@endif

Then ensure all those instances are in the same timezone to avoid surprises.

Upvotes: 1

Related Questions