What is Contextual Binding in Laravel?

Answer

Contextual binding allows you to inject different implementations of the same interface into different classes. Example: two controllers both type-hint FileSystem but one needs local storage and the other needs S3. In a service provider: $this->app->when(PhotoController::class)->needs(FileSystem::class)->give(fn() => Storage::disk("local")) and $this->app->when(VideoController::class)->needs(FileSystem::class)->give(fn() => Storage::disk("s3")). The container inspects which class is being constructed and provides the appropriate binding. You can also bind to a specific implementation only when a particular tagged service is needed. Contextual binding is essential for large applications where different parts of the app need different implementations of the same abstraction.