What is the Laravel Service Container?

What is the Laravel Service Container?

What is the Laravel Service Container?

Question

What is the Laravel Service Container and why is it important?

Answer

The Service Container (also called the IoC container) is the core of a Laravel application. It is responsible for resolving class dependencies and injecting them automatically wherever needed — controllers, jobs, commands, middleware, and more.

Instead of manually instantiating classes with new, you type-hint them in a constructor or method and Laravel resolves and injects them for you:

class OrderController extends Controller
{
    public function __construct(private OrderService $service) {}

    public function store(Request $request): JsonResponse
    {
        $order = $this->service->create($request->validated());
        return response()->json($order, 201);
    }
}

You can also bind interfaces to implementations in a service provider:

// AppServiceProvider::register()
$this->app->bind(PaymentGatewayInterface::class, StripeGateway::class);

Now anywhere PaymentGatewayInterface is type-hinted, Laravel will inject a StripeGateway instance. Swapping providers later requires changing only this one binding.

Key Bindings

  • bind() — new instance each time
  • singleton() — shared instance for the app lifetime
  • instance() — bind an already-created object
  • make() — manually resolve out of the container
All Comments