Going past Actions in Laravel
Published on by Steve McDougall
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.
Technical writer at Laravel News, Developer Advocate at Treblle. API specialist, veteran PHP/Laravel engineer. YouTube livestreamer.