Monday, April 10, 2017

Carbon Date formatting in Laravel

I have an array of Carbon Objects being passed to a view like so:

return view('booking.choose-days')->with(['weekDays' => $weekDays]);

To test that all is ok, I've DD'd the array and see that the arrays of dates are correctly being passed through:

array:14 [▼
  0 => Carbon {#252 ▼
    +"date": "2017-04-11 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "Europe/London"
  }
  1 => Carbon {#257 ▼
    +"date": "2017-04-12 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "Europe/London"
  }
  2 => Carbon {#256 ▼
    +"date": "2017-04-13 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "Europe/London"
  }
  3 => Carbon {#255 ▼
    +"date": "2017-04-14 00:00:00.000000"
    +"timezone_type": 3
    +"timezone": "Europe/London"
  }

...and so forth

When looping through the array in Blade using the following (full html left out):

@foreach ($weekDays as $key => $weekDay)
    <tr id="">
      <td>
        
      </td>
    </tr>
@endforeach

This produces the expected output of:

2017-04-11 00:00:00

2017-04-12 00:00:00

2017-04-13 00:00:00

2017-04-14 00:00:00

2017-04-15 00:00:00

...and so forth

However, when instead output:

@foreach ($weekDays as $key => $weekDay)
    <tr id="">
      <td>
         // now accessing a property
      </td>
    </tr>
@endforeach

I get an output of:

1 1 2 2 2

Instead of the expected 1,2,3,4,5 for Monday, Tuesday, Wednesday etc.

So the dates in the array are correct when var_dumped as objects, but when accessing a property like dayOfWeek, it's giving me incorrect properties.

Any idea why?

Thanks



via Ows

Advertisement