Skip to main content

Crate laravel

Crate laravel 

Source
Expand description

§Laravel for Rust

A full-stack web framework for Rust.

Most web applications need the same things: routing, validation, sessions, a database, queues, mail, and tests that exercise them. Laravel provides them in one crate, configured from the environment. This application serves a home page and a form handler that redirects back to it:

use std::process::ExitCode;

use laravel::prelude::*;

async fn home() -> &'static str {
    "Welcome to Laravel for Rust"
}

#[derive(serde::Deserialize)]
struct Profile {
    name: Option<String>,
}

async fn store(request: Request) -> laravel::Result<Redirect> {
    let name = request.parse::<Profile>()?.name.or_abort(422)?;
    // ...
    Ok(Redirect::route(home, ()))
}

fn web(route: &mut Router) {
    route.get("/", home);
    route.post("/users", store);
}

fn main() -> ExitCode {
    Application::configure()
        .with_routing(|routing, _| {
            routing.web(web);
        })
        .run()
}

An application starts with Application, and the prelude imports the types and traits most handlers use. The documentation has a guide for each feature.

Laravel is built on Axum. Handlers are Axum handlers, and any Axum extractor or tower layer works. The crate re-exports axum for applications that need to use Axum directly.

§Features

FeatureEnables
inertia (default)Inertia pages, in laravel::inertia
minijinja (default).html views in Jinja’s syntax, rendered by MiniJinja
database-sqlite, database-postgres, database-mysqlDatabase connections for each driver, in laravel::db, and models in laravel::model
redisRedis connections, in laravel::redis, and the redis cache store, session driver, and queue driver
s3S3-compatible file storage
sqsThe sqs and cloud queue drivers
sesThe ses mail transport
opentelemetryTrace export over OTLP, configured by the OTEL_* variables
reverbThe reverb:start command, which runs a Reverb server for local development
searchFull-text search over models, in laravel::search. It needs a database driver feature too

Enabling database without a driver feature is a compile error, so enable a driver feature instead.

Re-exports§

pub use crate::foundation::Application;
pub use axum;

Modules§

auth
Authentication: logging users in and out, and checking what they may do.
broadcast
Send your application’s events to the browser over WebSockets, so a page updates when an order ships or a teammate joins a room.
cache
Store slow results, such as a report or an API response, and read them back on later requests.
config
Typed configuration sections, read from the environment.
console
Write commands for jobs you run from a terminal or a scheduler, such as a nightly import or a one-off cleanup.
container
The service container, which builds the application’s services and shares them with the code that needs them.
context
The context of the work at hand: a request, a console command, a job, or work run with Application::scope.
cookie
Cookies, for small values the browser keeps between requests, such as a theme or a dismissed banner.
crypt
Authenticated encryption with the application’s keys.
db
Database connections, raw SQL, and transactions.
embed
Files compiled into the binary with embed!, such as a package’s views and assets.
errors
Reporting and rendering errors.
event
Events: typed values that listeners react to, with injected services.
feature
Feature flags let you ship code before everyone sees it, such as a new API that staff get first, then one customer in a hundred.
foundation
The application: configuring, building, and running it.
hash
Password hashing with bcrypt.
head
Search engines and link previews read a page’s <head>, so each page needs its own title, description, and share image, on top of defaults for the whole site.
http
Requests, responses, and middleware for the routes your application serves, and the client for the requests it sends.
inertia
Inertia lets you build a single-page app with React, Vue, or Svelte while your Rust handlers keep the routing, controllers, and data.
lottery
Odds of something happening, such as cleaning up expired sessions on 2 requests in 100, or giving a user a feature during a gradual rollout.
mail
Send email through Resend, Amazon SES, or a transport of your own.
model
Models, which are structs whose values are rows of a table, with typed columns and queries.
notification
Notify users by email, text message, Slack, and package channels.
numeric
Numeric types for application code, available with or without the database feature.
pagination
Pages of query results, with the links that move between them.
prelude
The traits and types most handlers and route files use, in one import:
process
Run other programs, such as git, ffmpeg, or a build script, and read what they wrote.
queue
Queues: jobs that run later, outside the request that dispatched them.
rate_limit
Rate limits for your own code, such as how many messages a user may send a minute or how many times someone may guess a password.
redis
Talk to Redis for counters, queues, pub/sub, and anything else you keep in memory across processes.
routing
Every request your application answers starts with a route that maps its method and URI to a handler.
schedule
Recurring tasks, such as a nightly report or an hourly cleanup, defined in Rust and run by a single cron entry.
search
Full-text search over models, with the index kept in step with model writes.
session
HTTP is stateless, so a session is how your application remembers a user from one request to the next, such as who is signed in or which message to show after a redirect.
slack
Build Slack messages with Block Kit, and handle their buttons and menus.
sms
Send text messages through Telnyx, or into the log.
storage
Keep the files your application stores, such as uploads and generated reports, on your server or in S3-compatible storage.
str
String helpers, random strings, and identifiers.
stream
Streams: values that arrive over time, such as the events of an EventStream.
task
Concurrent operations and tasks that keep the application’s context and tracing span.
testing
Tools for testing an application without starting a server.
time
Dates and times.
url
Generate URLs to routes, to paths, and to package assets.
validation
Validation for the input that requests submit.
view
Views keep your HTML in templates under resources/views, apart from the handlers that gather the data a page displays.
workflow
Durable workflows: a flow of steps written as one async function, which survives deploys, worker crashes, and sleeps of days in between.

Macros§

abort
Returns an HTTP error from the current function.
embed
Embed a directory’s files in the binary as an Embedded.

Structs§

Error
An error that handlers and middleware can return.

Constants§

VERSION
The framework version.

Traits§

ErrorContext
Attaches developer-facing context to a fallible operation while keeping the original error’s type and caller location.
OrAbort
Converts a missing value into an HTTP error.

Functions§

abort
Creates an HTTP error with the given status, as a number or a StatusCode.
abort_if
Returns an HTTP error with the given status when condition is true.
abort_unless
Returns an HTTP error with the given status unless condition is true.
abort_with
Creates an HTTP error with the given status and message.
config
Returns the application’s configuration, from anywhere in the application.
now
The current time in UTC.
once
Computes a value once per context and returns a clone of it.
once_for
Computes a value once per context and key, and returns a clone of it.
report
Reports an error and lets the caller carry on.
resolve
Resolves a service from the container, from anywhere the application runs.
view
A view to render with some data, returned from a handler or rendered with View::render.

Type Aliases§

Result
A Result whose error renders as an HTTP response.

Attribute Macros§

input
Declare a struct that a request fills.
notification
Make a notification from the impl block that holds its mail and sms methods.
once
Remember an async function’s result for the rest of the context, keyed by its arguments.
query
Declare a struct that a request’s query string fills.
test
Run a synchronous or asynchronous unit test, or an application test.