jeremy379 / laravel-disconnectable
Laravel Eloquent trait to disconnect models from the database at runtime
0.0.1
2025-09-04 13:59 UTC
Requires
- php: >=8.2
- laravel/laravel: ^12.4
Requires (Dev)
- illuminate/database: *
- phpunit/phpunit: ^12.3
README
Disconnect Laravel Eloquent models from their database connection at runtime.
Why this package?
In many applications following Clean Architecture or Hexagonal Architecture, you want to:
- Prevent database connections from leaking into the Domain or Application layers.
- Ensure models returned from the infrastructure layer are read-only and safe to use.
- Avoid accidental lazy-loading or persisting in views, services, or domain objects.
eloquent-disconnectable
provides a simple way to “cut” the database connection of a model or collection before returning it from repositories or infrastructure services, while keeping the original model attributes and already loaded relations accessible.
Benefits
- ✅ Prevents lazy-loading of relations.
- ✅ Prevents persistence operations (
save
,delete
,push
) on disconnected models. - ✅ Keeps already loaded relations accessible.
- ✅ Helps enforce Clean Architecture principles by isolating the domain from database concerns.
Installation
Require via Composer:
composer require jeremy379/eloquent-disconnectable
Usage
In a Model
use Illuminate\Database\Eloquent\Model; use YourVendor\EloquentDisconnectable\Disconnectable; class User extends Model { use Disconnectable; }
Disconnect a single model
$transaction = User::with('order')->first(); $disconnected = $transaction->disconnect(); // Access normal attributes echo $disconnected->id; // Access already loaded relations echo $disconnected->order->id; // Attempting DB operations will fail $disconnected->save(); // RuntimeException $disconnected->load('cart'); // RuntimeException $disconnected->otherRelation; // RuntimeException
Why and where to use it
- Infrastructure layer / repository: disconnect models before returning them to the Domain layer.
- Domain layer / services / controllers: ensures models are read-only and cannot accidentally hit the database.
- View / API layer: safe to render attributes and loaded relations without DB risk.
Clean Architecture Enforcement
+-------------------+
| Domain Layer |
| (Entities, DTOs) |
| - No DB access |
+-------------------+
↑
|
+-------------------+
| Infrastructure |
| (Repositories) |
| - DB access only |
+-------------------+
By disconnecting Eloquent models:
- Domain layer never touches the DB.
- Models are pure data objects for business logic.
- Already loaded relations are preserved, so performance stays optimal.
License
MIT © Jérémy Dillenbourg