Laravel, with its elegant syntax and robust features, has become the go-to framework for PHP developers. When it comes to working with databases and retrieving specific data, Laravel provides a range of tools to simplify the process. In this tutorial, we'll focus on fetching records from the last 7 days using Laravel's Eloquent ORM.

Prerequisites

Before we dive into the code, make sure you have Laravel installed and configured on your system.

Step 1: Create a Model

Assuming you have a database table that stores records with a timestamp (created_at), you'll want to create a model for that table. You can do this using the following Artisan command:

php artisan make:model Record

 

This command generates a new model file named "Record.php" in the "app\Models" directory.

 

Step 2: Define the Date Range

In your controller or wherever you need to fetch the last 7 days' records, you can define the date range using Carbon, a popular date and time library that Laravel uses by default:

use Carbon\Carbon;

$startDate = Carbon::now()->subDays(7);
$endDate = Carbon::now();

 

Here, we calculate the start date by subtracting 7 days from the current date and set the end date to the current date. Now see the complete code:

App\Http\Controllers\TutorialController.php

<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Models\Record;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TutorialController extends Controller
{
    public function __invoke(Request $request)
    {   

        $startDate = Carbon::now()->subDays(7);
        $endDate = Carbon::now();

        $records = Record::whereBetween('created_at', [$startDate, $endDate])->get();

        return $records;
    }
}

 

Conclusion

That's it! You've successfully fetched the last 7 days' records from your database using Laravel. This simple yet powerful technique can be incredibly useful in various scenarios, such as generating reports, displaying recent activities, or conducting data analysis.

Laravel's Eloquent ORM, combined with the flexibility of Carbon, makes working with date and time data a breeze. So go ahead, implement this feature in your Laravel project, and take full advantage of the framework's capabilities. Happy coding!

Category : #laravel

Tags : #laravel , #laravel query