Home > OS >  How can I loop to get dates of next 10 days from today using carbon in Laravel blade
How can I loop to get dates of next 10 days from today using carbon in Laravel blade

Time:10-22

I've been trying to create a dropdown of the next 10 days (along with the day optional) in Laravel blade.php I was able to get the current date using \carbon\carbon::now(); but when I try to add a day in the same variable it gives an error

Here is my Code-

<select class="form-control">
    <?php
     $today = \Carbon\Carbon::now()->format('m-d-Y (l)');
     $iterate = 0;
     for($iterate=0;$iterate<10;$iterate  ) {
    ?>
        <option value="{{$today}}">
           {{$today}}
        </option>
    <?php
     $today = $today->addDay(); } //this one isn't working
    ?>
</select>

The Error-
[2021-10-22 01:21:32] local.ERROR: Call to a member function addDay() on string (View: /var/www/vhosts/example.com/dummy.example.com/resources/views/superadmin/side_menu_superadmin.blade.php)

How can I work it out, Thanks in advance.

CodePudding user response:

You can use CarbonPeriod to generate range of dates. Try this code

@php
$now = Carbon\Carbon::now();
$startDate = $now->clone()->startOfDay();
$endDate = $now->clone()->addDays(10)->endOfDay();
//change 10 to whatever you needed
$datePeriod =  collect(Carbon\CarbonPeriod::create($startDate, $endDate)->toArray())
              ->map(function($eachCarbonDate){
                return $eachCarbonDate->format('m-d-Y (l)');
              });
@endphp

<select class="form-control">
  @foreach ($datePeriod as $eachFormattedDate)
      <option value="{{$eachFormattedDate}}">
           {{$eachFormattedDate}}
        </option>
  @endforeach
</select>

Here is the live demo link to phpsandbox

  • Related