PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 15, 2022

[FIXED] How to Display product offer for a limited period in Laravel

 November 15, 2022     eloquent, laravel, laravel-6, laravel-7, php-carbon     No comments   

Issue

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



Answered By - Kamlesh Paul
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing