Date formatting in Laravel

I have an array of Carbon objects being passed to a view like this:

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

      

To check that everything is ok, I DD'd the array and see that the date arrays are correctly 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 traversing an array in Blade using the following (full html):

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

      

This gives the expected output:

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, if instead you output:

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

      

I am getting output:

1
1
2
2
2

      

Instead of what is expected 1,2,3,4,5

for Monday, Tuesday, Wednesday

, etc.

So the dates in the array are correct when var_dumped

how objects

, but when accessing a property of the type, dayOfWeek

it gives me the wrong properties.

Dates are generated the first time they are read two timestamps

from the url - start date

and end date

. Both of these values ​​are then stored in variables and sent to the function to delete all outputs.

This is the function call:

$weekDays = getWeekDays(Carbon::createFromTimestamp($startDate), Carbon::createFromTimestamp($endDate));

      

And it has a function:

function getWeekDays(Carbon $startDate, Carbon $endDate)
{
    for($date = $startDate; $startDate->lte($endDate); $startDate->addDay()) {
        if ($date->isWeekDay()) {
            $weekdays[] = clone $date;
        }
    }

    return $weekdays;
}

      

Any idea why?

thank

+3


source to share


1 answer


Hello try this code:



 @foreach ($weekDays as $key => $weekDay)
<tr id="{{ $key }}">
  <td>
    {{    \Carbon\Carbon::parse($weekDay)->format('d/m/Y')->dayOfWeek }} // now accessing a property
  </td>
</tr>
 @endforeach

      

+1


source







All Articles