Learn all about Laravel's dependency injection container

Published on by

Learn all about Laravel's dependency injection container image

Laravel has a fantastic dependency injection container, yet many people shy away from it. In this tutorial, I will walk through how I lean on Laravels container to make my code work for me.

Using the container is all about being organized—having a consistent place to keep your container bindings and naming conventions that make sense and allow you to know what is going on. The container is only as good as the person sticking things into, after all.

Let's say we want to keep all our bindings in one place, in a service provider. Sounds sensible right? But what happens as our application grows? We start with maybe 5-6 bindings for a simple application, add several new features, and need to add bindings to the container. Before we know it, the service provider we are using is extremely large, and it takes a lot of cognitive effort to look for anything.

How can we combat this? How can we ensure that we aren't just sticking them in a service provider to hide the problem? Let me walk you through how I approach this.

My main AppServiceProvider is the entry point to my application, so my job is to register its key areas. I lean on Domain Driven Design, so I have one service provider per domain. I am allowing each domain to manage its bindings cleanly.

final class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->register(
provider: AuthDomainServiceProvider::class,
);
 
$this->app->register(
provider: CommunicationDomainServiceProvider::class,
);
 
$this->app->register(
provider: WorkDomainServiceProvider::class,
);
}
}

Using this approach, I can enable and disable domains as required, add a new one quickly, and get an overview of all the domains in my application from one file.

Of course, I keep the other default service providers with a Laravel application, as they have their purpose. So let us dive into one of the domain service providers to understand what it is used for.

final class AuthDomainServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->register(
provider: QueryServiceProvider::class,
);
 
$this->app->register(
provider: CommandServiceProvider::class,
);
 
$this->app->register(
provider: FactoryServiceProvider::class,
);
}
}

So my auth service provider is used purely to register the aspects of the domain that need to write their bindings.

Query - These are read operations in the application, common queries I need to run, or parts of queries I need to run. I wrote a tutorial on how I do this here.

Command - These are write operations in the application. Typically these will be pulled into background jobs so that the application can respond quickly.

Factory - These are Data Object factories. I find that data objects get big and messy and take up a lot of room. My solution to this was to move them to dedicated factories that I could use to create the data objects in my application.

Let's look at the CommandServiceProvider and how we might use this to register commands effectively within our application.

final class CommandServiceProvider extends ServiceProvider
{
public array $bindings = [
FindOrCreateUserContract::class => FindOrCreateUser::class,
GenerateApiTokenContract::class => GenerateApiToken::class,
SendPasswordResetContract::class => SendPasswordReset::class,
];
}

Laravel allows you to use the bindings property on a service provider to register any bindings that don't need arguments passed in. This keeps things clean in our service providers.

Let's look at one of these bindings to understand what they look like and are used for.

interface GenerateApiTokenContract
{
public function handle(Authenticatable $user, DataObjectContract $payload): Model|NewAccessToken;
}

Then we move on to the implementation.

final class GenerateApiToken implements GenerateApiTokenContract
{
public function handle(Authenticatable $user, DataObjectContract $payload): Model|NewAccessToken
{
return DB::transaction(
fn (): Model|NewAccessToken => $user->createToken(
name: $payload->name,
),
);
}
}

We wrap the write operation inside a database transaction, then use the injected user model and call the create token method on it, passing in the name property from our payload. This keeps things clean - as then you can also use this to generate API tokens for any user in your application, not just the currently logged-in user.

Using the container this way means my controllers are always clean and minimal. Let's look at an example API controller for logging in a user.

final readonly class LoginController
{
public function __construct(
private GenerateApiTokenContract $command,
private TokenNameGenerator $generator,
) {}
 
public function __invoke(LoginRequest $request): Responsable
{
$request->authenticate();
 
return new TokenResponse(
data: TokenFactory::make(
data: $this->command->handle(
user: auth()->user(),
payload: new TokenRequest(
name: $generator->generate(),
),
),
),
);
}
}

Of course, you are welcome to split this code a little, maybe giving it more breathing room. But to me, this is what I aim for. I am leaning on the container and using Laravel to my advantage by having small moving parts that combine to achieve an end goal.

Steve McDougall photo

Technical writer at Laravel News, Developer Advocate at Treblle. API specialist, veteran PHP/Laravel engineer. YouTube livestreamer.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Asymmetric Property Visibility in PHP 8.4 image

Asymmetric Property Visibility in PHP 8.4

Read article
Access Laravel Pulse Data as a JSON API image

Access Laravel Pulse Data as a JSON API

Read article
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article
Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3 image

Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3

Read article