Service Container:
Service Container is Laravel's dependency manager. It creates and manages objects automatically.
without service container
$db = new Database();
$user = new User($db);You create objects manually.
With Service Container:
$user = app(User::class);Laravel automatically creates the User object and its dependencies.
Service Provider:
A Service Provider is used to register services (classes) into the Service Container.
Service Provider is the central place where services, bindings, and event listeners are registered into the Service Container during application startup.
Example
Step 1: Create a Service
class PaymentService
{
public function pay()
{
return "Payment Success";
}
}Step 2: Register it in Service Provider
public function register()
{
$this->app->singleton(PaymentService::class, function ($app) {
return new PaymentService();
});
}Step 3: Use In Controller
class PaymentController
{
public function index(PaymentService $payment)
{
return $payment->pay();
}
}Register Service Approch:
| Method | Creates New Object? | Same Object? | Use Case |
|---|---|---|---|
bind() | ✅ Yes | ❌ No | Default registration |
singleton() | ❌ No | ✅ Yes | Database, Logger, Config |
instance() | ❌ No | ✅ Yes | Already-created object |
Direct bind(Class::class) | ✅ Yes | ❌ No | Simple classes |
| Interface Binding | Depends on bind or singleton | Depends | Best for dependency injection |
1. Using singleton() (Most Common):
public function register()
{
$this->app->singleton(PaymentService::class, function ($app) {
return new PaymentService();
});
}2. Using bind():
public function register()
{
$this->app->bind(PaymentService::class, function ($app) {
return new PaymentService();
});
}Difference:
bind() → New object every time
singleton() → Same object every time
3. Direct Class Binding:
Instead of using a closure, you can write:
public function register()
{
$this->app->bind(PaymentService::class);
}4. Using instance():
public function register()
{
$payment = new PaymentService();
$this->app->instance(PaymentService::class, $payment);
}5. Interface to Implementation (Recommended):
interface PaymentInterface
{
public function pay();
}class StripePayment implements PaymentInterface
{
public function pay()
{
return "Paid with Stripe";
}
}Register
public function register()
{
$this->app->bind(
PaymentInterface::class,
StripePayment::class
);
}Controller
class PaymentController
{
public function index(PaymentInterface $payment)
{
return $payment->pay();
}
}App Service Provider Structure:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
//
}
}