Laravel - How to return National Holidays in a specific format before sending to json

Viewed 101

In my Laravel-5.8, I am returning National Holidays as json request:

Controller:

$nationalholidays = HrHolidayDate::select('holiday_date')
    ->whereYear('created_at', '=', date('Y'))
    ->get()
    ->map(function ($nationalholiday) {
        return DateTime::createFromFormat('Y-m-d h:i:s', $nationalholiday->holiday_date)
                ->format('Y-m-d');
    });
return response()->json([
    'nationalholidays' => $nationalholidays,
]);

In the view blade, I have console.log(nationalholidays); as:

create:770 (2) ["2021-03-24", "2021-07-08"]0: "2021-03-24"1: "2021-07-08"length: 2__proto__: Array(0)

How do I change it into something like this:

natDays = [
  [1, 26], [2, 6], [3, 17],
  [4, 27], [5, 25], [6, 6],
  [7, 4], [8, 17], [9, 7],
  [10, 1], [11, 22], [12, 12]
];

So that it will consist of day and month separated by comma?

I want to use the reqult in jQuery-UI datepicker as shown here:

function nationalDays(date) {
    for (i = 0; i < natDays.length; i++) {
      if (date.getMonth() == natDays[i][0] - 1
          && date.getDate() == natDays[i][1]) {
        return [false, natDays[i][2] + '_day'];
      }
    }
  return [true, ''];
}
2 Answers

You already tried to change the format once.

->map(function ($nationalholiday) {
    return DateTime::createFromFormat('Y-m-d h:i:s', $nationalholiday->holiday_date)
            ->format('Y-m-d');
});

so you can change it again to your liking.

->map(function ($nationalholiday) {        
    return [
        $nationalholiday->holiday_date->month,
        $nationalholiday->holiday_date->day
    ];
});

Assuming holiday_date is Carbon class, if it's not you can cast it in your model.

// HrHolidayDate model

protected $casts = [
    'holiday_date' => 'date'
];

If you need array then you have to format it like array:

$nationalholidays = HrHolidayDate::select('holiday_date')
    ->whereYear('created_at', '=', date('Y'))
    ->get()
    ->map(function ($nationalholiday) {
        $datetime = DateTime::createFromFormat('Y-m-d h:i:s', $nationalholiday->holiday_date);
        return [
            $dateime->format('m'),
            $dateime->format('d'),
        ];
    });

return response()->json([
    'nationalholidays' => $nationalholidays,
]);

Also you can be one of the cool kids and use carbon instance:

$nationalholidays = HrHolidayDate::select('holiday_date')
    ->whereYear('created_at', '=', date('Y'))
    ->get()
    ->map(function ($nationalholiday) {
        $datetime = Carbon::parse($nationalholiday->holiday_date);
        return [
            $dateime->month,
            $dateime->day,
        ];
    });

return response()->json([
    'nationalholidays' => $nationalholidays,
]);

I recommend returning response as plain array if there is no reason to return as dataset:

return response()->json($nationalholidays);
Related