How to Get Last Month’s Records in Laravel?
Today we will learn How to Get Last Month’s Records in Laravel. In this tutorial, I will show you how to get last month to create data in the Laravel controller. In this tutorial, we will step by step create an example of how to get records for last month in Laravel.
Here, I will give you an example of how to get last month’s created records in Laravel. and we will use whereBetween()
with Carbon::now()->subMonth()->startOfMonth()
and Carbon::now()->subMonth()->endOfMonth()
Object in this example. We use Carbon::now()->subMonth()->startOfMonth() will return something like this: 2022-04-01 00:00:00
and Carbon::now()->subMonth()->endOfMonth() will return something like this: 2022-04-30 23:59:59
, so we use Laravel Model::whereBetween('created_at', [Carbon::now()->subMonth()->startOfMonth(), Carbon::now()->subMonth()->endOfMonth()])
will only return records created at.
Also read: How to Get Today Created Records in Laravel?
I created the posts table structure as below you can see.
Example
Also read: How to Get the Last 6 Month Data in Laravel?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Posts;
use Carbon\Carbon;
class HomeController extends Controller
{
public function index() {
$posts = Posts::select("*")->whereBetween('created_at', [Carbon::now()->subMonth()->startOfMonth(), Carbon::now()->subMonth()->endOfMonth()])->get()->toArray();
echo '<pre>';
print_r($posts);
}
}
Output
Array
(
[0] => Array
(
[id] => 1
[title] => how to integrate passport api in laravel
[body] => how to integrate passport api in laravel
[slug] => how-to-integrate-passport-api-in-laravel
[created_at] => 2022-04-23T15:19:50.000000Z
[updated_at] => 2022-04-23T15:19:50.000000Z
)
[1] => Array
(
[id] => 3
[title] => how to force redirect http to https using htaccess
[body] => how to force redirect http to https using htaccess,how to force redirect http to https using htaccess,how to force redirect http to https using htaccess
[slug] => how-to-force-redirect-http-to-https-using-htaccess
[created_at] => 2022-04-23T15:19:50.000000Z
[updated_at] => 2022-04-23T15:19:50.000000Z
)
[2] => Array
(
[id] => 7
[title] => laravel eloquent wherenotbetween example
[body] => laravel eloquent wherenotbetween example, laravel eloquent wherenotbetween example, laravel eloquent wherenotbetween example
[slug] => laravel-eloquent-wherenotbetween-example
[created_at] => 2022-04-25T15:19:50.000000Z
[updated_at] => 2022-04-25T15:19:50.000000Z
)
)