Laravel global query scopes with database views

Carlos Mendez Jan 2026
4 tabs
<?php

namespace App\Scopes;

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

class TenantScope implements Scope
{
    public function apply(Builder $builder, Model $model): void
    {
        if ($tenantId = auth()->user()?->tenant_id) {
            $builder->where($model->getTable() . '.tenant_id', $tenantId);
        }
    }
}
4 files · php Explain with highlit

Combining global scopes with database views creates powerful data access patterns for multi-tenancy and security. Global scopes automatically filter all queries for a model—perfect for tenant isolation or active record filtering. I implement the Scope interface with an apply() method. Database views present filtered/joined data as virtual tables. Laravel models can query views like regular tables. For complex reporting, views aggregate data efficiently. Materialized views cache expensive computations. The combination enables row-level security—users only see their data. I use views for legacy database integration, exposing normalized structures. This architecture separates data access concerns from business logic.