Search code examples
laraveleloquentlaravel-6laravel-7php-carbon

How to Display product offer for a limited period in Laravel


I need to display as as the product Status is special for a selected date from X date to X date,

This is how my UI Looks like enter image description here

This is the place where a user can create a new sub category and select a special offer dates

enter image description here

This is my Show Function in my Controller

 public function show(Category $category)
{
    // ! Search Filter
    $filter = new SearchFilter();
    $filter->where('parent_id','=',$category->id);

    // ! Date Filter (Today)
     $day = Carbon::now();
     $today = $day->toDateString();
   

    return view('manage.categories.show')->with([
        'pageTitle' => $category->name,
        'allItems' => $this->dataRepo->search([], $filter),
        'isDestroyingEntityAllowed' => $this->isDestroyingEntityAllowed,
        'entity' => $category,
        'today'=>$today,
    ]);
}

This is my blade where it checks the date

@foreach ($allItems as $item)
            <td>
                @if ($item->special_start == $today || $item->special_end == $today)
                    Special
                    @else
                    Regular
                @endif
            </td>

    @endforeach

But this will show Special only if it matches the date with start date and end date, the days between the start date and the end date will be shown as Regular.

How can i fix it ?


Solution

  • Use Carbon it is not recommended to write logic in view but you can move this to controller

    @foreach ($allItems as $item)
    <td>
        @php
            $first = \Carbon\Carbon::create($item->special_start);
            $second = \Carbon\Carbon::create($item->special_end);
            $diff = now()->between($first, $second);
        @endphp
        @if ($diff)
        Special
        @else
        Regular
        @endif
    </td>
    @endforeach
    

    ref link https://carbon.nesbot.com/docs/#api-comparison