Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

asdasdsa's avatar

Depending on date, add a class to a blade view from a partial

Hi!

So im trying to change class on an element depending on specific dates.

Im grabbing some json from the database

["2017-06-24","2017-06-25","2017-06-26"]

And as you can see in this example, I have yesterday (24), today (25) and tomorrow (26).

And because I have today in the interval of available dates, I want to append success class. (If it was the 24th today or 26th, I also want the success class)

If these dates has passed, I want to append warning, if they have not passed (future), I don't want to append anything.

I have a partial that I have been struggling with

@foreach(json_decode($event->date) as $date)
    @php
        $parsed_date = \Carbon\Carbon::createFromFormat('Y-m-d', $date);
    @endphp
    @if($parsed_date->isSameDay(\Carbon\Carbon::now()))
        class="success"
    @elseif($parsed_date->isPast())
        class="warning"
    @endif
@endforeach

But when in between dates, I cannot get it to work properly. How can I achieve this?

0 likes
5 replies
JackRobertson's avatar

If the dates are always grouped together, you might want to consider querying a date range vs a list of dates.

For example:

if (current date is between start date and end date) {
    append success class
} elseif (date is before start date) {
    append warning class
}
Snapey's avatar

If you are storing these dates just for this one check then maybe you could simplify things by storing the middle date and then just querying if date field is today, yesterday or tomorrow then success, otherwise warning.

Carbon has methods for all of those.

As it is, you are iterating over the three dates and outputting a class each time so even if it worked you would get class="warning" three times if the dates are in the past

asdasdsa's avatar

How about this solution

@php
    $array =json_decode($event->date); // ["2017-06-24"]
    $first_date = \Carbon\Carbon::createFromFormat('Y-m-d',current($array));
    $last_date = \Carbon\Carbon::createFromFormat('Y-m-d',end($array));
@endphp

@if(in_array(\Carbon\Carbon::now()->format('Y-m-d'), $array))
    class="success"
@elseif($last_date->isPast())
    class="warning"
@endif 
Snapey's avatar

what about checking for current date?

asdasdsa's avatar

@Snapey Yes I'm doing that

in_array(\Carbon\Carbon::now()->format('Y-m-d')

Or what do you mean?

Please or to participate in this conversation.