Home > Software engineering >  add day name format on array in laravel
add day name format on array in laravel

Time:04-07

i want to change the date to format ('l Y-m-d'), i mean to add the day name, for example Friday 2022-04-01 in the array, is it possible to add the day name in it? date in still in the form 2022-04-01, how to add the name of the day? when i return result from $holiday like this

enter image description here

my code in index.blade.php

//to get date range from query start_date end_date
 @php
      $start_date = \Carbon\Carbon::parse(request()->query('start_date '))->format('Y-m-d');
      $end_date = \Carbon\Carbon::parse(request()->query('end_date'))->format('Y-m-d');
                            
      $dateRangePeriod = \Carbon\CarbonPeriod::create($start_date , $end_date);
      $dateRange = [];
      foreach ($dateRangePeriod as $key => $date) {
            $dateRange[] = $date->format('Y-m-d');
      }
 @endphp

 @foreach ($dateRange as $key => $range)
      @php

         $holiday = array_filter(json_decode($company_holiday, true), function ($var) use ($range) {
               return $var['date'] == $range;
         });

         $holiday = reset($holiday);

         dd($holiday);

       @endphp
  @endforeach

my code in controller

$company_holiday = CompanyHoliday::where('company_holiday.company_id', $company_id)
            ->whereDateBetween('company_holiday.date', $date_start, $date_end)
            ->get();

CodePudding user response:

You can use Accessor for this

https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor

// in CompanyHoliday Model

 //define accessor
public function getDayNameAttribute()
{
    return Carbon::parse($this->date)->format('l Y-m-d');
}


//get accessor in loop 
 $company_holiday->dayName

if you want dayName always with Holiday then use appends property in CompanyHoliday Model

https://laravel.com/docs/8.x/eloquent-serialization#appending-values-to-json

protected $appends = ['day_name'];

CodePudding user response:

make the changes in the blade file.

    @php

        use Carbon\Carbon;


        $range = '2022-04-01';
        $date = Carbon::parse($range)->format('D Y-m-d'); // "Fri 2022-04-01"

    @endphp

for more formating refere: Carbon Docs

  • Related