Ad

Laravel & Carbon - Loop Data Range

- 1 answer

I would like to list all the day between two dates with Carbon. Here the code:

 @foreach ($rooms as $room)
  <div class="col-sm-4">
        <div class="card">
          <img class="card-img-top" data-src="holder.js/100px180">
          <div class="card-block">
            <h4 class="card-title">{{$room->type}}</h4>
            <p class="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum reiciendis facere repellat soluta obcaecati laborum ex perspiciatis, iusto.</p>
          </div>
          <ul class="list-group list-group-flush">
            <li class="list-group-item">
                <ul>
                    //////HERE THE PART TO LIST EACH DAY//////
                    @for($d = 0; $d < $checkin->diffInDays($checkout); $d++)
                     <li>{{$checkin->addDay()->toDateString()}}</li>
                    @endfor
                   //////////////////////////////////////////////

                </ul>
            </li>
          </ul>
          <div class="card-block">
             <button type="submit" class="btn btn-primary btn-lg btn-block" name="room_id" value="{{ $room->id }}">Book</button>
          </div>
        </div>
    </div>
    @endforeach

Here is what happens (in this test the $checkin = 2015-12-16 and the $checkout = 2015-12-19):

enter image description here

It is obvious that for each card should be a list with:

  • 2015-12-16
  • 2015-12-17
  • 2015-12-18

I know I could use the php classes (like DatePeriod, DateInterval, ecc..) but I would like to find a good solution with Carbon.

Making some test, it is like Carbon saves the change of the date.

Ad

Answer

You could try to clone the $checkin object like this:

<?php $date = clone $checkin; ?>

@while ($date->diffInDays($checkout))
    <li>{{$date->toDateString()}}</li>

    <?php $date->addDay(); ?>
@endwhile

Or better:

@for ($date=clone$checkin; $date->diffInDays($checkout)>0; $date->addDay())
    <li>{{$date->toDateString()}}</li>
@endfor
Ad
source: stackoverflow.com
Ad