Skip to main content

How to Get Last N Days Records in Laravel?

When querying data from last x days, it’s important to consider the size and complexity of the data set. In some cases, you may only need the most recent record or a few records from the past x days. Other times, you may need to query a larger data set that spans a longer period of time.

There are a variety of ways to query data from the past x days. In Laravel, you can use the Carbon class to work with dates and time intervals. For example, the following code will get the most recent record from the past X days:

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Carbon\Carbon;

class UserController extends Controller
    public function index()
        $half_month_ago = Carbon::now()->subDays(15);
        $sales = User::where('order_date', '>=', $half_month_ago )->get();

$latestInvoices = DB::table('invoices')
                     ->where('created_at', '>=', Carbon::now()

Both of these approaches have their advantages and disadvantages. It’s important to choose the right approach for your data and use case. If you only need a few records from the past x days, using Carbon may be the simplest and most efficient solution. If you need to query a large data set, using Laravel’s query builder may be more scalable.

By continuing to use the site, you agree to the use of cookies.