Laravel Service Container Explained
Laravel Service Container: Tips & Tricks
Laravel Service Container: Tips & Tricks
Tip: You Rarely Need to Bind Anything
Thanks to auto-wiring, most classes resolve automatically. Only bind when:
- You need an interface → implementation mapping
- You need a singleton
- You need contextual binding
Gotcha: Circular Dependencies
If class A needs B and B needs A, you'll get a binding resolution exception. Break the cycle with events or a third mediator class.
Tip: Use #[Bind] Attribute Instead of Service Providers
#[Bind(RedisCache::class)]
interface CacheInterface {}
No need to register in a service provider anymore.
Tip: Contextual Binding for Different Implementations
$this->app->when(PhotoController::class)
->needs(Filesystem::class)
->give(fn() => Storage::disk('local'));
$this->app->when(VideoController::class)
->needs(Filesystem::class)
->give(fn() => Storage::disk('s3'));
Gotcha: The Container Resolves Fresh Instances
Unless you use singleton(), every make() call creates a new instance. This can be surprising when you expect state to persist.
Tip: Use bound() to Check Before Resolving
if ($this->app->bound(PaymentGateway::class)) {
$gateway = $this->app->make(PaymentGateway::class);
}
Tip: Tagging for Multiple Implementations
$this->app->tag([CpuReport::class, MemoryReport::class], 'reports');
$reports = $this->app->tagged('reports');
Great for plugin architectures.
Tip: Use route:cache Carefully
php artisan route:cache is fast, but it doesn't work with closure-based routes. Every time you cache routes, Laravel serializes them. If you have Route::redirect() or closure callbacks, the cache breaks. Stick to controller-based routes in production.
Tip: Model APP_KEY Rotation
Rotating APP_KEY invalidates all encrypted data — cookies, encrypted DB columns, and password reset tokens. If you must rotate (e.g., after a leak), plan a migration that re-encrypts existing data with the new key.
Gotcha: Local Scope Leaks
Global scopes defined in booted() apply to ALL queries on that model — including relationships. An innocent User::all() in admin panel might exclude soft-deleted users if a global scope is active.
Senior Insight
Package selection is one of the most consequential decisions in a Laravel project. I evaluate packages on three criteria: (1) test coverage and CI quality, (2) responsiveness to issues and PRs, and (3) commitment to backward compatibility. A package that breaks on every Laravel upgrade will cost more in maintenance than the feature is worth. For critical infrastructure (payment processing, authentication), I prefer first-party Laravel packages over community alternatives.
Source: Laravel News (https://laravel-news.com/), Freek.dev (https://freek.dev/tags/laravel), Spatie Blog (https://spatie.be/blog)