Back to All Nuggets
Laravel php ⏱️ 2 min read
Production Implementation
Ask endoAI
<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class Subscription extends Model
{
    public function scopeActive(Builder $query): Builder {
        return $query->where('status', 'active')
                     ->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>=', now()));
    }

    public function scopeExpiringWithinDays(Builder $query, int $days = 7): Builder {
        return $query->where('status', 'active')
                     ->whereBetween('expires_at', [now(), now()->addDays($days)->endOfDay()]);
    }
}

DRY Database Querying with Local and Dynamic Scopes

When multiple endpoints filter active subscriptions, hospital quotes, or pending payments, copying raw where() clauses causes bugs. Eloquent Scopes centralize complex filtering logic onto the Model.

Accelerate Your Engineering Career

Get monthly masterclasses, exclusive code snippets, and direct architectural reviews.

Become a Supporter • KES 500 / Month