Laravel Get Last N Days Records

Published on October 20, 2020 22 sec read

HIRE US 🖐
We're available to do freelance project. Take a look at our services!

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. 🙂

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

Leave a Reply

Your email address will not be published. Required fields are marked *