How to Get the Last 6 Month Data in Laravel?
Today we will learn How to Get the Last 6 Month’s Data in Laravel. In this tutorial, I will show you how to get the last 6 month’s created data in the Laravel controller. we can get 6 months of created records in the Laravel 8 application.
Here, I will give you an example of how to get the last 6 month’s records in Laravel. and we will use whereBetween()
with Carbon::now()->subMonth(6)
and Carbon::now()
Object in this example. Here, Carbon::now()->subMonth(6)
will return something like this: 2021-11-04 11:51:31
and Carbon::now()
will return something like this: 2022-05-04 11:52:10
, so we use Laravel Model::whereBetween('created_at', [Carbon::now()->subMonth(6), Carbon::now()])
will only return records created at.
Also read: How to Get Today Created Records in Laravel?
I create the posts table structure as below you can see.
Example
<?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(6), Carbon::now()])->get()->toArray();
echo '<pre>';
print_r($posts);
}
}
Also read: How to Get Last Month Records in Laravel?
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
)
)
Good tutorial, I’m very happy to read this post, and most useful.
thank you.