Polyscope - The agent-first dev environment for Laravel

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

Educator and Content creator, freelance consultant, API evangelist

Cube

Laravel Newsletter

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

image
Jump24 - UK Laravel Agency

Laravel Developers that Click into Place. Never outsourced. Never offshored. Always exceptional.

Visit Jump24 - UK Laravel Agency
Bacancy logo

Bacancy

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

Bacancy
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
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
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

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

Lucky Media
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

The latest

View all →
The Inertia v3 Beta is Here image

The Inertia v3 Beta is Here

Read article
Polyscope Is an Ai-First Dev Environment for Orchestrating Agents image

Polyscope Is an Ai-First Dev Environment for Orchestrating Agents

Read article
Filament v5.3.0 Released with Deferred Tab Badges and Column Manager Improvements image

Filament v5.3.0 Released with Deferred Tab Badges and Column Manager Improvements

Read article
Ward: A Security Scanner for Laravel image

Ward: A Security Scanner for Laravel

Read article
Kit: An Opinionated API Starter Kit for Laravel image

Kit: An Opinionated API Starter Kit for Laravel

Read article
Livewire v4.2.0 Released with Security Hardening and Laravel 13 Support image

Livewire v4.2.0 Released with Security Hardening and Laravel 13 Support

Read article