
# Laractions - Actions for Laravel Rust
<p align="center">
<a href="https://github.com/edulazaro/laractions-rust/actions/workflows/tests.yml"><img src="https://github.com/edulazaro/laractions-rust/actions/workflows/tests.yml/badge.svg" alt="Tests"></a>
<a href="https://crates.io/crates/laractions"><img src="https://img.shields.io/crates/v/laractions" alt="Crates.io"></a>
<a href="https://crates.io/crates/laractions"><img src="https://img.shields.io/crates/d/laractions" alt="Downloads"></a>
<a href="https://docs.rs/laractions"><img src="https://img.shields.io/docsrs/laractions" alt="Docs.rs"></a>
<a href="https://github.com/edulazaro/laractions-rust/blob/main/LICENSE.md"><img src="https://img.shields.io/crates/l/laractions" alt="License"></a>
</p>
> Encapsulate your business logic into clean, reusable structs that run **synchronously or asynchronously** in Laravel Rust.
## Introduction
**Laractions** is a crate that introduces an **action-based pattern** for Laravel Rust applications. Actions encapsulate specific pieces of logic that can be executed synchronously or asynchronously, keeping your handlers and models clean.
Instead of placing business logic in handlers, models, or services, **actions** allow you to encapsulate reusable operations in self-contained structs.
It is the port of [Laractions](https://github.com/edulazaro/laractions), the PHP package, to [Laravel Rust](https://laravel.com/rust). **It targets Laravel Rust 0.1, which is in beta, and its API follows the framework's changes until 1.0.** The names, the call shapes and this document follow the PHP package. Where Rust has no equivalent, the section says so, and the [differences](#differences-from-the-php-package) are collected at the end.
- Supports standalone and model-scoped actions
- Allows asynchronous execution with queues
- Provides a `make:action` generator for quick creation
### Why use actions?
Instead of bloating **handlers**, **models**, or **services**, Laractions keeps logic **encapsulated** and **reusable**.
| Feature | Laractions |
|---------|-----------|
| **Encapsulation** | Keeps business logic clean and reusable |
| **Async execution** | Supports Laravel Rust queues and retries |
| **Validation** | Validates the arguments before execution |
| **Model-bound** | Works directly with your models |
| **Fluent API** | `run()`, `dispatch()`, `retry()`, `queue()` |
---
## Installation
Laractions requires Laravel Rust 0.1 and the 2024 edition. Add the crate, and `serde`, which every action derives:
```bash
cargo add laractions serde --features serde/derive
```
Register the service provider in `src/app.rs`. It adds the `make:action` and `list:actions` commands, and the `action_traces` migration if you ask for it:
```rust
use laractions::LaractionsServiceProvider;
use laravel::Application;
use laravel::foundation::ApplicationBuilder;
pub fn configure() -> ApplicationBuilder {
Application::configure().with_providers(|providers| {
providers.add(LaractionsServiceProvider::new());
})
}
```
The PHP package publishes its migration with the `laractions-migrations` tag. Here `with_migrations()` registers it, and you only need it for [tracing](#enabling-tracing):
```rust
providers.add(LaractionsServiceProvider::new().with_migrations());
```
Nothing else is required: `#[action]` registers each action when the application is built, as `#[job]` does for jobs.
## Naming
Name the struct whatever you want to read at the call site. `make:action` uses the name you give it, unchanged:
```bash
laravel make:action SendEmail # struct SendEmail
laravel make:action SendEmailAction # struct SendEmailAction
```
Both conventions are in use. `SendEmail` reads well because the `actions` module already carries the intent, the way Laravel names `jobs::SendEmail` rather than `SendEmailJob`. `SendEmailAction` reads well because the suffix survives the import. Pick one and keep it.
## Creating actions
You can write an action by hand or use the **console command**:
```bash
laravel make:action SendEmail
```
This writes `src/actions/send_email.rs`, declares it in `src/actions/mod.rs`, and gives you this basic action:
```rust
use laractions::action;
use serde::{Deserialize, Serialize};
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct SendEmail {}
#[action]
impl SendEmail {
async fn handle(&self) -> laravel::Result<()> {
// Implement action logic here
Ok(())
}
}
```
If `src/lib.rs` does not declare `pub mod actions;` yet, the command tells you to.
You will place the logic inside the `handle` method, with the arguments it needs:
```rust
#[action]
impl SendEmail {
async fn handle(&self, email: String, subject: String, message: String) -> laravel::Result<()> {
// Your action logic here
Ok(())
}
}
```
You can then run the action via the `run` method. `Action` must be in scope, as it is where `create()` comes from:
```rust
use laractions::Action;
SendEmail::create().run(("user@example.com", "Welcome!", "Hello User")).await?;
```
`handle` may return the value itself or a `laravel::Result` of it, and `run` hands that value back:
```rust
let sent: String = SendEmail::create().run(("user@example.com", "Welcome!", "Hello User")).await?;
```
### How `run()` maps arguments to `handle()`
PHP maps the arguments of `run()` to `handle()` by reflection. Rust has no reflection, so `#[action]` reads the parameters of `handle` at compile time and `run()` matches the arguments to them by name or by position, with the same rules. You can call it in three ways:
```rust
// Positional
SendEmail::create().run(("user@example.com", "Welcome!", "Hello User")).await?;
// Named arguments
SendEmail::create()
.run(args! { email: "user@example.com", subject: "Welcome!", message: "Hello User" })
.await?;
// Associative array, mapped to parameters by name
SendEmail::create()
.run(json!({
"email": "user@example.com",
"subject": "Welcome!",
"message": "Hello User",
}))
.await?;
```
`args!` builds named arguments, the closest Rust has to `email: 'user@example.com'`. `json!` is `serde_json`'s. A single value is passed as it is, `run("Bob")`, and no arguments are `run(())`.
When `handle()` declares **more than one parameter**, the keys of an associative array are matched to the parameter names (the last example above). A list, such as a `Vec`, fills the parameters in order.
When `handle()` declares **a single parameter that accepts a whole array** (`serde_json::Value`, a map, a `Vec` or a set, or an `Option` of one), the array is passed through whole as that one argument, the "attribute bag" pattern:
```rust
#[action]
impl CreateInvoice {
async fn handle(&self, attributes: Value) -> String {
attributes["concept"].as_str().unwrap_or_default().to_owned()
}
}
CreateInvoice::create().run(json!({ "concept": "x", "amount": 10 })).await?;
```
When the single parameter is a **concrete type** (a struct or a scalar, such as `handle(&self, file: String)`), a single array is **not** treated as the bag: its keys are mapped by name, and a single value is passed positionally. A struct serializes to the same JSON object as an array does, which PHP cannot confuse with an object, so a struct goes inside a tuple, where it is always one positional argument:
```rust
ProcessFile::create().run(json!({ "file": file })).await?; // mapped by name
ProcessFile::create().run((file,)).await?; // positional
```
Arguments left out arrive as `None` in an `Option` parameter, and as an error naming the parameter otherwise. PHP has default values in `handle()` where Rust has `Option`, so the default goes in the body:
```rust
async fn handle(&self, name: String, email: Option<String>) -> String {
format!("{name}_{}", email.unwrap_or_else(|| "bob@example.com".to_owned()))
}
```
When a single associative array matches **none** of `handle()`'s parameters and leaves a required one empty, the error says so and names the call to make, instead of a bare "invalid type: null":
```text
DataAndOption::handle() received a single array whose keys (a, b) match none of its parameters (data, monitor), so `data` was left empty. If the array is meant as one argument, pass it by name: run(args! { data: .. }).
```
### Dependencies
PHP resolves the action through the container, so its constructor receives services. Rust actions are built with `Default`, and the services reach `handle` as `Inject<T>` parameters, which Laravel Rust resolves from the container. They are not arguments of `run()`:
```rust
use laravel::container::Inject;
#[action]
impl SendEmail {
async fn handle(&self, email: String, subject: String, mailer: Inject<Mailer>) -> laravel::Result<()> {
mailer.send(&email, &subject).await
}
}
SendEmail::create().run(("user@example.com", "Welcome!")).await?;
```
### Validation
The `$rules` array becomes `rules(..)` in the attribute, with the same pipe-separated strings:
```rust
#[action(rules(name = "required|string", email = "required|string|email"))]
impl Register {
async fn handle(&self, name: String, email: String) -> String {
format!("{name}_{email}")
}
}
```
The arguments are validated after they are matched to the parameters, before `handle` runs. A failure is the validation error Laravel Rust renders everywhere else: a `422` for an API client, a redirect back for a browser form, and an `InvalidInput` you can `downcast_ref` to.
The rules Laractions understands are `required`, `filled`, `present`, `nullable`, `sometimes`, `bail`, `accepted`, `declined`, `string`, `numeric`, `integer`, `boolean`, `array`, `email`, `url`, `uuid`, `ulid`, `ip`, `ipv4`, `ipv6`, `json`, `alpha`, `alpha_num`, `alpha_dash`, `lowercase`, `uppercase`, `confirmed`, `same:x`, `different:x`, `in:a,b`, `not_in:a,b`, `min:n`, `max:n`, `between:a,b`, `gt:x`, `gte:x`, `lt:x`, `lte:x`, `date`, `regex:/../`, `starts_with:a,b` and `ends_with:a,b`. As in Laravel, `min`, `max` and `between` read the length of a string, the value of a number when `numeric` or `integer` is also there, and the number of items when `array` is. A rule it does not know, such as `exists:users,id`, fails with an error naming it, rather than being skipped.
## Creating model actions
You can write a model action by hand or use the **console command**:
```bash
laravel make:action SendEmail --model=User
```
This writes `src/actions/user/send_email.rs`:
```rust
use laractions::action;
use serde::{Deserialize, Serialize};
use crate::models::User;
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct SendEmail {
#[serde(skip)]
#[allow(dead_code)]
user: Option<User>,
}
#[action(model = User)]
impl SendEmail {
async fn handle(&self) -> laravel::Result<()> {
// Implement action logic for user here
Ok(())
}
}
```
The user instance will be available inside the `user` field. PHP finds the property by the model's class name, and Rust finds the field by the type named in `model = User`, which is the snake case of the type: `user`, `blog_post`. The field is an `Option`, because an action exists before it is bound, and `#[serde(skip)]` keeps the model out of the queue payload: the worker loads it again.
`--model` takes `User`, which becomes `crate::models::User`, or a full path such as `crate::billing::Invoice`.
Models using actions implement the `HasActions` trait. The `$actions` array becomes `actions()`:
```rust
use laractions::{HasActions, actions};
impl HasActions for User {
fn actions() -> Actions {
actions! { "send_email" => SendEmail }
}
}
```
Now, you can execute the action by its key:
```rust
user.action_named("send_email")?.run(("user@example.com", "Welcome!", "Hello User")).await?;
```
Alternatively, you can still call the action type directly so you do not have to list it:
```rust
user.action::<SendEmail>().run(("user@example.com", "Welcome!", "Hello User")).await?;
```
`action::<SendEmail>()` is typed, and `run` returns what `handle` returns. `action_named("send_email")` looks the action up at run time, so it cannot know the type: `run` returns a `Box<dyn Any + Send>` to `downcast` to what `handle` returns.
## Dynamic parameters
Laractions provides a flexible `with()` method to set action fields dynamically:
```rust
let action = SendEmail::create().with(args! {
email: "user@example.com",
subject: "Welcome!",
message: "Hello User",
});
```
This avoids passing long parameter lists in the `run()` method. Please note that these values are set as fields of the action, so the struct declares them, and `handle` reads them as `self.email`. A name the struct has no field for is ignored, as PHP ignores it. A value of the wrong type is an error when the action runs:
```rust
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct SendEmail {
pub email: String,
pub subject: String,
}
#[action]
impl SendEmail {
async fn handle(&self) -> String {
format!("{} to {}", self.subject, self.email)
}
}
SendEmail::create().with(args! { email: "user@example.com", subject: "Welcome!" }).run(()).await?;
```
## Actions and models
When calling an action from a model, the model is automatically bound to the action:
```rust
user.action::<SendEmail>().run(()).await?;
```
If the `SendEmail` action declares `model = User`, the action will automatically get the model in its `user` field:
```rust
#[action(model = User)]
impl SendEmail {
async fn handle(&self) -> laravel::Result<()> {
let user = self.user.as_ref().expect("the action runs on a user");
tracing::info!("welcoming {}", user.email);
Ok(())
}
}
```
`on()` does the same for an action you created yourself, and `get_actionable()` returns the model's reference, its morph name and its key:
```rust
SendEmail::create().on(&user).run(()).await?;
```
## Running actions asynchronously
Laractions allows dispatching actions asynchronously as jobs:
```rust
SendEmail::create()
.queue("high")
.delay(10)
.retry(5)
.dispatch(("user@example.com", "Welcome!", "Hello User"))
.await?;
```
This queues the action instead of executing it immediately. The job is created and linked to the action, so you do not need to define it. `dispatch` returns the job's id, and `dispatch_sync` runs the action through its job on the spot.
You can configure how actions are dispatched as jobs, once, on the action. The `$tries`, `$delay` and `$queue` properties become options of the attribute:
```rust
#[action(tries = 5, delay = 30, queue = "emails")]
impl SendEmail {
// ...
}
```
`retry()`, `delay()` and `queue()` override them for one dispatch.
### What goes into the queue
PHP serializes the action object into the job, with the models as references that it loads again. The job here is a single type, `ActionJob`, registered as `laractions.action`, and it carries:
- the action's name, which `#[action]` registered,
- the action itself serialized as JSON, which is what `with()` set,
- the arguments exactly as `dispatch` received them,
- the model and the actor as a morph name and a key,
- the tries, and whether logging and tracing are on.
That makes the **inputs of a queued action serializable**: the arguments and the action's fields go through `serde`, and anything that cannot, such as a connection, belongs behind `Inject<T>` in `handle` or in a `#[serde(skip)]` field. A model is skipped from the payload and bound again by the worker, which loads it by its key, so it is fresh when the action runs. If the row is gone the job fails with `ModelNotFound`, as PHP's does with `ModelNotFoundException`. The model must be one the action declares with `model = ..`.
Laravel Rust fixes a job's retries on its type, and PHP sets them for each dispatch, so the job allows up to 100 attempts and counts the action's own `tries` itself. Past the action's tries, the job fails for good: Laravel Rust records it in `failed_jobs`, and `failed()` logs it:
```text
[ActionJob: app::actions::SendEmail] Job failed: the mail server is down
```
In tests the `sync` driver runs the action where it is dispatched and returns its error from `dispatch`, as PHP's sync queue throws it.
## Testing
Fake the queue to see what was dispatched. The job's fields are the action's name, the arguments, the model, and the tries:
```rust
use laractions::ActionJob;
use laravel::queue;
#[laravel::test]
async fn it_queues_the_email(app: Application) -> laravel::Result<()> {
let jobs = queue::fake();
SendEmail::create().queue("high").retry(3).dispatch(("user@example.com", "Welcome!", "Hi")).await?;
jobs.assert_pushed_where::<ActionJob>(|job| {
job.queue() == "high" && job.tries == 3 && job.action.ends_with("SendEmail")
});
Ok(())
}
```
Run the job itself with `app.job(..)`, and a real worker with `app.command("queue:work --stop-when-empty")` against the `database` connection, as this crate's own tests do.
PHP's `mockAction()` is deprecated there in favour of binding a double in the container, and there is no Rust counterpart: put the service an action uses behind `Inject<T>` and register a double of the service.
## List available actions
To list all registered actions in your application, run:
```bash
laravel list:actions
```
PHP scans `app/Actions`. Here the list is what `#[action]` registered, by name.
## Logging actions
Enable logging for any action:
```rust
SendEmail::create()
.enable_logging()
.dispatch(("user@example.com", "Welcome!", "Hello User"))
.await?;
```
The dispatch is logged through `tracing`, with the queue, the delay, the tries and the arguments, and so lands wherever your Laravel Rust log channel writes. Inside `handle`, `self.log("message")` writes `[Action: <name>] message` the same way.
## Acting as an actor
You can make any model an actor (like a User) by implementing the `IsActor` trait:
```rust
use laractions::IsActor;
impl IsActor for User {}
```
Then, call actions like this:
```rust
user.act::<SendInvoice>()
.on(&order)
.trace()
.run(())
.await?;
```
This automatically sets the actor on the action before executing it. `act_named("name")` takes an action by its registered name.
## Enabling tracing
Tracing is disabled by default, and needs the migration (`with_migrations()` on the provider, then `laravel migrate`). You can enable it per action like this:
```rust
SendEmail::create()
.trace()
.run(("user@example.com", "Welcome!", "Hello!"))
.await?;
```
You can assign the actor and the actionable model like so:
```rust
SendEmail::create()
.actor(&user)
.on(&target)
.trace()
.run(params)
.await?;
```
Each successful run writes a row to `action_traces`, readable through the `ActionTrace` model: the actor and the target as a morph name and a key, the action's name, and the arguments as JSON.
```rust
let traces = ActionTrace::query().get().await?;
```
## Differences from the PHP package
- **An action is a struct with `#[action]` on its impl**, not a subclass of `Action`. Rust has no inheritance and no reflection, so the attribute reads `handle` and generates what `Action` does in PHP. The struct derives `Default`, `Serialize` and `Deserialize`.
- **`create()` is `Default`**, not the container. Services reach `handle` as `Inject<T>` parameters instead of the constructor.
- **`handle` is never `protected`**: it is a private method of the impl, which is how `#[job]` works too.
- **`run()` takes one argument that stands for PHP's argument list**: a tuple for positional arguments, `args! { .. }` for named ones, `json!({..})` for an array. The matching rules are PHP's. A struct is passed in a tuple, because it cannot be told from an array otherwise.
- **`run()` and `dispatch()` are `async`**, and return a `laravel::Result`. `dispatch()` returns the job id instead of `void`, and there is a `dispatch_sync()`.
- **`handle()` has no default values.** Use `Option`, which receives `None` where PHP would use `null`.
- **Properties become attribute options**: `$tries`, `$delay`, `$queue` and `$rules` are `tries = ..`, `delay = ..`, `queue = ..` and `rules(..)`, and `$actions` is `HasActions::actions()`.
- **The model field is an `Option`**, declared with `model = User` in the attribute, and skipped by serde. PHP finds it by reflecting on the properties and the parent classes, and a model that no `model = ..` declares is recorded as the actionable but not bound.
- **`with()` sets fields through serde**, and a bad value is reported when the action runs, not by `with()`.
- **`enableLogging(bool)` and `trace(bool)` are `enable_logging()` and `trace()`**, with `enable_logging_as(bool)` and `trace_as(bool)`, because Rust has no default arguments.
- **`$user->action('key')` is `user.action_named("key")`**, and `$user->action(SendEmail::class)` is `user.action::<SendEmail>()`. The first cannot be typed, so its result is `Box<dyn Any + Send>`.
- **Queued retries**: PHP gives the job `$tries` per instance. Laravel Rust fixes `tries` on the job type, so the job allows 100 and counts the action's own (see [what goes into the queue](#what-goes-into-the-queue)). There is no backoff, as in PHP.
- **Queued actions are named `laractions.action`** in `queue:work`, `queue:failed` and the failed jobs table. The action's name is in the payload.
- **Validation** takes the pipe syntax for the rules in the list above. Laravel Rust has no validator that takes Laravel's rule strings, so they are translated, and a rule that cannot be is an error.
- **Traces store their keys as text**, so a model with a UUID key can be traced. PHP's `nullableMorphs` columns are integers. `with_migrations()` registers the migration instead of `vendor:publish`.
- **`list:actions` lists names**, from the registry, not files from the `app/Actions` folder.
- **No `__invoke`, no `mockAction()`, no LaraClaude skills**: the first has no Rust form, the second is deprecated in PHP, and the skills read the PHP API.
- **There is no config file**, in PHP either.
## Sponsors
Laractions for Laravel Rust is supported by the following sponsors. Thank you for keeping it growing:
<p>
<a href="https://kenodo.com"><img src="art/logo-kenodo.png" width="24" alt="Kenodo"></a> <a href="https://kenodo.com">Kenodo</a>
<a href="https://andorradev.com"><img src="art/logo-andorradev.png" width="24" alt="AndorraDev"></a> <a href="https://andorradev.com">AndorraDev</a>
</p>
## Author
Created by [Edu Lazaro](https://edulazaro.com)
## License
Laractions for Laravel Rust is open-sourced software licensed under the [MIT license](LICENSE.md).