Today in this tutorial you will learn How to get First and Last Day of current or previous Month with Carbon. Carbon provide us to all type get first, last day of the previous or current month or anything with easiest way.
BTW If you are using laravel 5 below laravel app then you need to install carbon package otherwise in laravel 6, laravel 7, laravel 8 or laravel 9 has predefault installed the carbon package. Best we have added 3 best examples for Laravel Carbon Get Last Day of the Month;
Example 1:
Here we are use carbon pacakge just like ” use Carbon\Carbon; ” then use the current day time use “Carbon::now()”, you can get the right not date and times just use “now()”.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Carbon\Carbon;
class CalenderController extends Controller
{
public function getLastDayOfTheMonth()
{
$today = Carbon::now(); // can use now() laavel 6+ above version
$lastDayofMonth = Carbon::parse($today)->endOfMonth()->toDateString();
echo "<pre>"; print_r($lastDayofMonth); die;
}
}
Example 2:
Same this example return last day of the current month.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Carbon\Carbon;
class CalenderController extends Controller
{
public function getLastDayOfTheMonth()
{
$lastDayofMonth = Carbon::now()->endOfMonth()->toDateString();
echo "<pre>"; print_r($lastDayofMonth); die;
}
}
Example 3:
Below example return same output same as above examples:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Carbon\Carbon;
class CalenderController extends Controller
{
public function getLastDayOfTheMonth()
{
$lastDayofMonth = Carbon::now()->endOfMonth()->modify('0 month')->toDateString();
echo "<pre>"; print_r($lastDayofMonth); die;
}
}
Above examples output will be:
// This month is december 2021
//output
2021-10-31
I hope this example help you.. if you have any other ideas please comment!