Laravel Cloud is here! Zero-config managed infrastructure for Laravel apps. Deploy now.

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
Curotec

Curotec helps software teams hire the best Laravel developers in Latin America. Click for rates and to learn more about how it works.

Visit Curotec
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
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
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
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
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
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
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 →
Laravel 12.44 Adds HTTP Client afterResponse() Callbacks image

Laravel 12.44 Adds HTTP Client afterResponse() Callbacks

Read article
Handle Nested Data Structures in PHP with the Data Block Package image

Handle Nested Data Structures in PHP with the Data Block Package

Read article
Detect and Clean Up Unchanged Vendor Files with Laravel Vendor Cleanup image

Detect and Clean Up Unchanged Vendor Files with Laravel Vendor Cleanup

Read article
Seamless PropelAuth Integration in Laravel with Earhart image

Seamless PropelAuth Integration in Laravel with Earhart

Read article
Laravel API Route image

Laravel API Route

Read article
Laravel News 2025 Recap image

Laravel News 2025 Recap

Read article