Explain Contextual Binding and how does it work in Laravel?

Custom Validation

Sometimes you may have two classes that utilize the same interface, but you wish to inject different implementations into each class. For example, two controllers may depend on different implementations of the Illuminate\Contracts\Filesystem\Filesystem contract. Laravel provides a simple, fluent interface for defining this behavior:

use Illuminate\Support\Facades\Storage;
use App\Http\Controllers\PhotoController;
use App\Http\Controllers\VideoController;
use Illuminate\Contracts\Filesystem\Filesystem;

$this->app->when(PhotoController::class)
->needs(Filesystem::class)
->give(function () {
return Storage::disk(‘local’);
});

$this->app->when(VideoController::class)
->needs(Filesystem::class)
->give(function () {
return Storage::disk(‘s3’);
});

Leave a Reply

Your email address will not be published. Required fields are marked *