Going past Actions in Laravel

Published on by

Going past Actions in Laravel image

Over the last year or so, the Action based approach has been gaining popularity in the Laravel world. I was a big fan of this and adopted it relatively early on.

However, as time passed, I found that I was sticking everything imaginable under the Actions namespace, and the directory was getting increasingly packed. I went from trying to simplify my process to extracting everything into actions - and finding the right one was getting more complicated each time.

I decided to do something about it, find a way that would allow me to still benefit from this approach, but without everything being classed as an action. Having used various architectural patterns before, I thought back to some of the ones that worked well for me. I was a big fan of CQRS (Command Query Responsibility Segregation). However, I didn't like the manual approach of adding all of my mappings so that I could lean on the Command Bus or Query Bus. But I could take what I liked about this pattern and lean on Laravels container to do what I needed.

So I decided to take what I classed as Actions and split these into something closer to the CQRS approach. Commands are the write actions that I want to perform, and Queries are my read actions. Let's look at an example of these changes.

namespace App\Actions;
 
final class CreateNewUserAction
{
public function handle(NewUser $user): Model|User
{
return DB::transaction(
callback: static fn () => User::query()->create($user->toArray()),
attempts: 2,
);
}
}

This is a typical example of what a write action would look like. It would accept a DTO as its payload and perform a write query inside a database transaction. This worked well for me, but what does it look like as a Command instead?

namespace App\Commands\Users;
 
final class CreateNewUser
{
public function handle(NewUser $user): Model|User
{
return DB::transaction(
callback: static fn () => User::query()->create($user->toArray()),
attempts: 2,
);
}
}

It is the same thing but under a different namespace, so I have better separation in my code. You could approach actions similarly and create nested namespaces - but you wouldn't get the same segregation of intent as you do when you split read and write operations. Let me go through a more complex example next.

You will understand the process if you read my tutorial on Modelling Business Processes in Laravel. Let's assume we have a process where we want to create a new team for our users. The steps we take for this are as follows:

  • Create a new team model.
  • Attach our user as a team member.
  • Email our users to notify them.
  • Set up any additional resources required for a team, perhaps billing.

This is large if you look at it within a controller, and if you use actions or even commands and queries - you end up with many things being pulled into one place, naming gets messy, and you aren't gaining much benefit. Instead, I use a different approach and build out a process. A lot of what we do in our applications are processes, a sequential list of things that need doing to achieve a result. This is no different. First, look at the underlying code - the abstract process we want to implement.

abstract class Process
{
protected array $tasks = [];
 
public function run(object $payload): mixed
{
return Pipeline::send(
passable: $payload,
)->through(
pipes: $this->tasks,
)->thenReturn();
}
}

All we want to do is create a collection of tasks we want to run - meaning that processes can share tasks without code duplication. Then we run all of this through the pipeline facade.

How does this relate to commands and queries, though? Let's dive into our example.

final class TeamCreationProcess extends Process
{
protected array $tasks = [
CreateNewTeam::class,
AssignNewTeamMember::class,
NotifyTeamOwnerOfNewMember::class,
SetupBillingForTeam::class,
];
}

In our controller, all we need to do is:

final class StoreController
{
public function __construct(
private readonly TeamCreationProcess $process,
) {}
 
public function __invoke(StoreRequest $request): Responsable
{
$this->process->run($request->payload());
 
return new MessageResponse(
message: 'Your team has been created',
);
}
}

Pretty clean, right? Let's look at a few of these tasks to see where we are leaning on the commands and queries.

final class CreateNewTeam
{
public function __construct(
private readonly NewTeamCreation $command,
) {}
 
public function __invoke(object $payload, Closure $next): mixed
{
$this->command->handle($payload);
 
return $next($payload);
}
}

Our tasks can call our commands instead of implementing the same logic. You could add the write action within here. However, by still using a command - you can create a new team from the API, Web, and CLI easily without it being wrapped in a process. If you had a simple CLI command, you most likely want to avoid a process - you want a quick action.

The approach I am using now is from lessons learned in building different types of applications, and while it can be a bit of leg work to create multiple classes to achieve the one thing - as your application grows, you will be thankful for having done it. By breaking down what we need into a process, we can fine-tune this process over time by adding additional steps - without affecting what is happening. I don't know if there is an architectural term for this approach, but it is one that I like very much.

My FormRequest is responsible for creating the payload I want to pass through. My process is accountable for the tasks I want to run through. My tasks are responsible for calling the correct read or write action, and my read and write operations only need to worry about reading or writing data. It is all small, well-built, and unit-testable pieces of code that are easy to replicate and refactor without adversely affecting my entire application.

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.

image
Laravel Forge

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

Visit Laravel Forge
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

Bespoke software solutions built for your business. We ♥ Laravel

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
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with VILT and TALL stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a 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
Rector logo

Rector

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

Rector

The latest

View all →
Anonymous Event Broadcasting in Laravel 11.5 image

Anonymous Event Broadcasting in Laravel 11.5

Read article
Microsoft Clarity Integration for Laravel image

Microsoft Clarity Integration for Laravel

Read article
Apply Dynamic Filters to Eloquent Models with the Filterable Package image

Apply Dynamic Filters to Eloquent Models with the Filterable Package

Read article
Property Hooks Get Closer to Becoming a Reality in PHP 8.4 image

Property Hooks Get Closer to Becoming a Reality in PHP 8.4

Read article
Asserting Exceptions in Laravel Tests image

Asserting Exceptions in Laravel Tests

Read article
Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4 image

Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4

Read article