In web development, working with databases is a common task. Laravel, a popular PHP framework, provides a powerful set of tools for interacting with databases. One common requirement is to retrieve records that belong to the current week. In this blog post, we will explore how to fetch records from a database using Laravel that are associated with the current week.

In this example tutorial, we will explore how to fetch this week's records in Laravel using Eloquent. Laravel offers a variety of functions for working with dates and times. To get records for the current week, we'll make use of these date functions, such as whereBetween and between.

Here, we write the query of laravel to get this week's records. 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)
    {   
        $records = Record::whereBetween(
                DB::raw('DATE(billing_date)'),
                [
                    Carbon::now()->startOfWeek(Carbon::SUNDAY),
                    Carbon::now()->endOfWeek(Carbon::SATURDAY)
                ]
            )->sum('net_bill');

        return $records;
    }
}

 

This code will retrieve all records from the "records" table where the "billing_date" date falls between the start and end of the current week.

 

Read also: Laravel Fetch Last 7 Days Records: A Handy Guide

 

Conclusion

In this blog post, we've learned how to fetch records from a database using Laravel that belong to the current week. By utilizing Laravel's date functions, you can easily filter and retrieve the data you need. This is just one example of the many powerful features Laravel offers for database interactions. Whether you are building a simple to-do list application or a complex e-commerce platform, Laravel's elegant syntax and rich toolset make it a great choice for web development.

Category : #laravel

Tags : #laravel , #laravel query