Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Carbon class changing my original variable value

I'm trying to make a few navigation buttons in a calendar type thing I'm creating, and I'm using carbon to create the dates.

This is the code in the controller:

if ($date == null) {     $date = \Carbon\Carbon::now(); } else {     $date = \Carbon\Carbon::createFromFormat('Y-m-d', $date); } $navDays = [     '-7Days' => $date->subDay('7')->toDateString(),     '-1Day'  => $date->subDay('1')->toDateString(),     'Today'    => $date->today()->toDateString(),     '+1Day'  => $date->addDay('1')->toDateString(),     '+7Days' => $date->addDay('7')->toDateString() ]; 

and then I'm my view, I'm doing this:

@foreach($navDays as $key => $i)     <li>         <a href="/planner/bookings/{{ $i }}" class="small button">             {{ $key }}         </a>     </li> @endforeach 

This problem is, that carbon seems to change the $date during the array creating, because these are the dates I'm getting(with $date being set to 2015-11-29):

<ul class="button-group even-5">     <li><a href="/planner/bookings/2015-11-22" class="small button">-7Days</a></li>     <li><a href="/planner/bookings/2015-11-21" class="small button">-1Day</a></li>     <li><a href="/planner/bookings/2015-12-22" class="small button">Today</a></li>     <li><a href="/planner/bookings/2015-11-22" class="small button">+1Day</a></li>     <li><a href="/planner/bookings/2015-11-29" class="small button">+7Days</a></li> </ul> 

Does anybody know what I'm doing wrong?

like image 382
Johan Björklund Avatar asked Dec 22 '15 10:12

Johan Björklund


1 Answers

When you run these methods against a Carbon object it updates the object itself. Therefore addDay() moves the value of Carbon one day forward.

Here's what you need to do:

$now = Carbon::now();  $now->copy()->addDay(); $now->copy()->addMonth(); $now->copy()->addYear(); // etc... 

The copy method essentially creates a new Carbon object which you can then apply the changes to without affecting the original $now variable.

To sum up, the methods for copying a Carbon instance are:

  • copy
  • clone - an alias of copy

Check out the documentation: https://carbon.nesbot.com/docs/

like image 77
diggersworld Avatar answered Oct 14 '22 02:10

diggersworld