skip to Main Content

I have selected a month from month field

<input class="form-control" type="month" id="report_month" name="report_month"
                                               value="{{ old('report_month') }}">

That value is ‘2023-02’.

How to get last date of that specific month in controller?

Value required is :2023-02-28

2

Answers


  1. $input = $request->input('report_month'); // 2023-02
    [$year, $month] = explode('-', $input);   // [2023, 02]
    today()->setYear($year)->setMonth($month)->endOfMonth()->format('Y-m-d');
    

    or

    Carbon::createFromFormat('Y-m', $request->validated('report_month'))
        ->endOfMonth()->format('Y-m-d');
    
    Login or Signup to reply.
  2. @php  
    $lastDayofMonth1 = CarbonCarbon::createFromFormat('Y-m', $request->input('report_month'))->endOfMonth()->day;
    @endphp 
    

    another ways

    @php  $lastDayofMonth = CarbonCarbon::now()->modify('-2 month')->endOfMonth()->toDateString(); @endphp
    

    used ->modify('-2 month') part is dynamically, we get values

    OR

    @php  
    $month = 5;
    $lastDayofMonth =CarbonCarbon::today()->setMonth($month)->endOfMonth()->day;
    @endphp  
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search