Laravel Get Last N Days Records

Published on October 20, 2020 22 sec read

Hi artisan, sometimes we need to get 7, 15 or 30 days of data from the database. In this short article, I’m going to share how to get the last N days data in Laravel. Let’s see an example:

TestController.php
<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Carbon\Carbon;
use Illuminate\Http\Request;

class TestController extends Controller
{
    public function index() {
        $last_n_days = 7;
        $posts = Post::whereBetween('date', [
            Carbon::now()->subdays($last_n_days)->format('Y-m-d'),
            Carbon::now()->subday()->format('Y-m-d')
        ])->get();

        dd($posts);
    }
}

In the example, we got the last 7 days posts from database.

That’s it. Thanks for reading. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.
Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow