Laravel 10: Laravel, a popular PHP framework, provides a sophisticated ORM for database queries. There is a requirement in many applications to access data using certain date ranges, such as "today"
, "yesterday"
, "last 7 days"
or bespoke periods. Rather than having to deal with raw SQL, Laravel offers an attractive solution via "Eloquent ORM"
. In this detailed article, we’ll look at how to setup and use date scopes in Laravel 10 to easily get data using date filters.
1. Exploring the Power of Date Scopes in Laravel 10
Laravel’s date scopes allow you to filter database records depending on time periods. These custom methods, which allow you to filter records based on certain dates or date ranges, can be built within your models or throughout your codebase. You could, for example, construct a date scope called "today"
to retrieve all data created on the current day. Date scopes are extremely useful when working with time-sensitive data or designing applications like as analytics tools or e-commerce platforms.
I’ll assume in this post that you’re creating a simple URL shortener service and need to display data like clicks and visitors depending on user-selected date ranges.
2. Database Setup and Model Configuration
To begin, let’s establish a database and a model for tracking visits to the shortened URLs. This model will be known as "Visits"
. You can accomplish this by issuing the following commands:
php artisan make:model Visits -m
Let’s now add the logic to the Visits model and its migration file. The model should resemble this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Visits extends Model
{
use HasFactory;
protected $fillable = [
'ip', 'metadata', 'link_id', 'country'
];
protected $casts = [
'metadata' => 'array',
];
public function links()
{
return $this->belongsTo(Links::class, 'link_id');
}
}
The migration file should resemble this:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('visits', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('link_id')->index();
$table->string('ip');
$table->string('country')->nullable();
$table->json('metadata');
$table->timestamps();
$table->foreign('link_id')->references('id')->on('links')->cascadeOnDelete();
});
}
public function down()
{
Schema::dropIfExists('visits');
}
}
3. Creating Date Scopes for Precise Data Queries
Now that we have our model in place, let’s add date scopes to make data retrieval easier depending on certain date periods. This logic will be encapsulated in a separate class named DateFilter. The class contains methods for collecting date ranges for a variety of time periods, including "today"
, "yesterday"
, and custom date ranges. The DateFilter class is as follows:
// App/Utils/DateFilter.php
<?php
namespace App\Utils;
use Exception;
use Illuminate\Support\Carbon;
class DateFilter
{
public static function getDatesForPeriod($period, $customStart = null, $customEnd = null)
{
switch ($period) {
// ... (date range cases omitted for brevity)
case 'custom':
if ($customStart && $customEnd) {
$start = Carbon::parse($customStart)->startOfDay();
$end = Carbon::parse($customEnd)->endOfDay();
} else {
throw new Exception('Custom range requires start and end dates.');
}
break;
default:
throw new Exception('Invalid period specified.');
}
return ['start' => $start, 'end' => $end];
}
}
Carbon, an elegant date library, is used by this class to determine the start and end dates based on the supplied period.
4. Leveraging Date Scopes in Database Queries
Let’s use our date scope helper to efficiently query the database now that we have it. We wish to obtain database entries based on the timeframe selected by the user. In our model, we’ll add a function called results to do this:
<?php
use App\Models\Visits;
public static function results($period, $customStart = null, $customEnd = null)
{
$dates = self::getDatesForPeriod($period, $customStart, $customEnd);
return Visits::with('links')
->whereBetween('created_at', [$dates['start'], $dates['end']])
->get();
}
Eloquent is used in this code to retrieve results when the "created_at"
column is inside the provided date range. You may easily acquire date-filtered data by invoking this function with the desired timeframe.
5. Wrapping It Up: Simplifying Data Retrieval in Laravel 10
Finally, Laravel’s date scopes provide a powerful method for filtering database records based on certain time ranges. You may efficiently get data relevant to your application’s requirements by building custom date scopes and utilizing Eloquent’s capability. These strategies will help you simplify your data retrieval operations whether you’re creating a URL shortener or an analytics application. Simplify your code, improve the efficiency of your application, and easily offer consumers with the data they require.
Many times we come across 419 Page Expired Error in Laravel 10. I’ve created a article Demystifying and Resolving the 419 Page Expired Error in Laravel 10 where I discussed about the 419 in Laravel 10.
Happy Coding !