Singleton vs Binding in Laravel: When and Why to Use Them
🔹 What is bind()?
bind() creates a new instance every time it is resolved.
Example
$this->app->bind(PaymentService::class, function () {
return new PaymentService();
});
Now if you resolve it twice:
app(PaymentService::class);
app(PaymentService::class);
👉 You get two different objects.
When to Use bind()
Use it when:
- Object holds temporary state
- You need a fresh instance each time
- It should not share data
Example:
- Payment processing
- File uploads
- Data transformers
🔹 What is singleton()?
singleton() creates only one instance for the entire request lifecycle.
Example
$this->app->singleton(SettingsService::class, function () {
return new SettingsService();
});
Now even if you resolve it multiple times:
app(SettingsService::class);
app(SettingsService::class);
👉 You get the same object every time.
When to Use singleton()
Use it when:
- The object should be shared
- It stores configuration or cached data
- It manages shared state
Example:
- App settings loader
- Logger instance
- Configuration manager