Alex Garrett-Smith

Alex Garrett-Smith



Actions in Laravel. Single-task classes that are easy to test and keep reusability high. In this thread, we'll run through some high level stuff and get to grips with how actions might improve the architecture of our Laravel apps. Let's gooo 👏

What's an action? Simply put, a single class that does one thing. An action could create a post, update a user, process a SaaS subscription – pretty much anything you're already doing in your apps. The benefit? Smaller units of code that are easier to re-use and test.

I use the brilliant Laravel Actions package by @lorismatic. This package allows you to generate and create actions that run as controllers, listeners and more. It also includes built-in testing helpers for mocking actions, making them way easier to test.

The simplest action looks like this. It's a class with a handle method, where we pass in any arguments we need to fulfil the action. The IsAction trait exposes all of the functionality of the Laravel Actions package.

How do we run actions? There are a few ways. You can make an action by resolving it then running it, run it right away, or resolve it from the container through dependancy injection.

Now, this is where the magic begins ✨ We're not limited to using this action on it's own, we can also register and run it as a controller.

Where does validation fit in? We validate directly from the action!

What about route model binding and authorization? Here's a stripped back example of creating an order for a user. The user ID is passed into the URL, resolved with route model binding, and authorized 👍

In the previous example, we have an action that can be run as a controller, but also on its own. In a real-world scenario, your app could allow users to register (as a controller) and your admins could register users (as a direct call to the action). Literally zero duplication.

Actions can also be run as event listeners, console commands and jobs, meaning your actions are now multi-purpose and you don't need to duplicate any code, or spend time creating separate Laravel classes. One class, handling everything.

In that previous example, you can now send an order email with an event, manually send an order email using an Artisan command, or (of course), run the action on it's own from anywhere.

There's a load more functionality baked into this package. If you enjoy screencasts and want to learn more, I'm covering Laravel Actions over on @teamcodecourse right now. See you there 👋

Follow us on Twitter

to be informed of the latest developments and updates!

You can easily use to @tivitikothread bot for create more readable thread!
Donate 💲

You can keep this app free of charge by supporting 😊

for server charges...