Open source December 2026
Laractions Rust

Laractions Rust

Laractions Rust

Laractions Rust gives every meaningful operation in your app its own struct: one handle method, called the same way from a handler, a console command or a test, and moved onto a queue by changing one word. It runs on Laravel Rust.

Written against version 0.1, which targets Laravel Rust 0.1 (in beta). Its API follows the framework's changes until 1.0.

This is the port of Laractions, the PHP package, and its names and call shapes follow it. The crate is on crates.io and its API reference is on docs.rs. For a step-by-step tutorial in Spanish, see Cómo usar acciones en Laravel Rust on Neoguias.

Installation

cargo add laractions

Register the service provider in src/app.rs. It adds the make:action and list:actions commands:

use laractions::LaractionsServiceProvider;

pub fn configure() -> ApplicationBuilder {
    Application::configure().with_providers(|providers| {
        providers.add(LaractionsServiceProvider::new());
    })
}

Tracing is the one feature that needs a table. LaractionsServiceProvider::new().with_migrations() registers the action_traces migration, which replaces the PHP package's vendor:publish. Nothing else is required: #[action] registers each action when the application is built, as #[job] does for jobs.

Writing an action

laravel make:action SendEmail

This writes src/actions/send_email.rs, declares it in src/actions/mod.rs and tells you to add pub mod actions; to src/lib.rs if it is missing. An action is a struct with #[action] on its impl:

use laractions::action;
use serde::{Deserialize, Serialize};

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct SendEmail {}

#[action]
impl SendEmail {
    async fn handle(&self, email: String, subject: String) -> laravel::Result<()> {
        Ok(())
    }
}

Run it with run, where Action must be in scope because create() comes from it. handle may return the value itself or a laravel::Result of it, and run hands that value back:

use laractions::Action;

SendEmail::create().run(("user@example.com", "Welcome!")).await?;

Passing arguments

PHP maps the arguments of run() to handle() by reflection. Rust has none, so #[action] reads the parameters of handle at compile time and run() matches the arguments by name or by position, with the same rules:

SendEmail::create().run(("user@example.com", "Welcome!")).await?;
SendEmail::create().run(args! { email: "user@example.com", subject: "Welcome!" }).await?;
SendEmail::create().run(json!({ "email": "user@example.com", "subject": "Welcome!" })).await?;

When handle has a single parameter that takes a whole array (serde_json::Value, a map, a Vec), the array is passed through whole, the attribute bag pattern. When it is a concrete type, such as a String, the keys of an array are mapped by name. A struct goes inside a tuple, run((file,)), because it cannot be told from an array otherwise. Arguments left out arrive as None in an Option parameter and as an error naming the parameter otherwise. A single array that matches none of the parameters gets an error that says so.

with() sets fields of the action instead, and handle reads them as self.email:

SendEmail::create().with(args! { email: "user@example.com" }).run(()).await?;

Rust actions are built with Default, so services reach handle as Inject<T> parameters, resolved from the container. They are not arguments of run().

Validation

The $rules array becomes rules(..) in the attribute, with the same pipe-separated strings:

#[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 and a redirect back for a browser form. The rules understood include required, string, numeric, integer, boolean, array, email, url, uuid, in:a,b, min:n, max:n, between:a,b, confirmed, date, regex:/../ and the usual comparisons. A rule it does not know, such as exists:users,id, fails with an error naming it instead of being skipped.

Model actions

laravel make:action SendEmail --model=User

The action declares its model in the attribute, and the model is bound to the field named after its type (user, blog_post), which is an Option skipped by serde:

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct SendEmail {
    #[serde(skip)]
    user: Option<User>,
}

#[action(model = User)]
impl SendEmail {
    async fn handle(&self) -> laravel::Result<()> {
        let user = self.user.as_ref().expect("the action runs on a user");

        Ok(())
    }
}

A model implements HasActions to name its actions, as $actions does in PHP:

impl HasActions for User {
    fn actions() -> Actions {
        actions! { "send_email" => SendEmail }
    }
}

user.action_named("send_email")?.run(()).await?;
user.action::<SendEmail>().run(()).await?;

action::<SendEmail>() is typed and run returns what handle returns. action_named looks the action up at run time, so run returns a Box<dyn Any + Send> to downcast. on(&user) binds a model to an action you created yourself.

Asynchronous actions

dispatch queues the action instead of running it, and returns the job's id:

SendEmail::create()
    .queue("high")
    .delay(10)
    .retry(5)
    .dispatch(("user@example.com", "Welcome!"))
    .await?;

Defaults go on the action, and the call overrides them for one dispatch:

#[action(tries = 5, delay = 30, queue = "emails")]
impl SendEmail {
    // ...
}

There is no job to write. Every queued action is one ActionJob, named laractions.action in queue:work and queue:failed, that carries the action's name, the action serialized as JSON, the arguments, the model and the actor as a morph name and a key, and the tries. The inputs of a queued action therefore have to be serializable. A model is skipped from the payload and loaded again by the worker, and if the row is gone the job fails with ModelNotFound.

Laravel Rust fixes a job's retries on its type, so the job allows up to 100 attempts and counts the action's own tries itself. Past them the job fails for good, lands in failed_jobs and is logged. dispatch_sync runs the action through its job on the spot.

Actors and tracing

Implement IsActor on a model and it can act. Tracing is off by default, needs the migration above and is enabled per run:

user.act::<SendInvoice>()
    .on(&order)
    .trace()
    .run(())
    .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. actor(&user) and on(&target) set them on an action you created yourself.

Logging

enable_logging() logs the dispatch through tracing, with the queue, the delay, the tries and the arguments. Inside handle, self.log("message") writes [Action: <name>] message the same way, so it lands wherever your Laravel Rust log channel writes. list:actions lists every registered action by name.

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:

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!")).await?;

    jobs.assert_pushed_where::<ActionJob>(|job| {
        job.queue() == "high" && job.tries == 3 && job.action.ends_with("SendEmail")
    });

    Ok(())
}

Run a real worker with app.command("queue:work --stop-when-empty") against the database connection. There is no mockAction(): put the service an action uses behind Inject<T> and register a double of the service.

Differences from the PHP package

  • An action is a struct with #[action] on its impl, not a subclass. 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.
  • run() takes one argument that stands for PHP's argument list: a tuple for positional arguments, args! { .. } for named ones, json!({..}) for an array.
  • 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(..). $actions is HasActions::actions().
  • The model field is an Option, declared with model = User and skipped by serde. PHP finds it by reflection.
  • with() sets fields through serde, and a bad value is reported when the action runs.
  • $user->action('key') is user.action_named("key"), and $user->action(SendEmail::class) is user.action::<SendEmail>().
  • Queued retries: Laravel Rust fixes tries on the job type, so the job allows 100 and counts the action's own. There is no backoff, as in PHP.
  • Validation takes the pipe syntax for the rules in the list above. A rule that cannot be translated is an error.
  • Traces store their keys as text, so a model with a UUID key can be traced.
  • 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.

built and maintained by Edu Lazaro · MIT license