Laravel Get Last N Days Records

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