Skip to main content

laravel/
lib.rs

1//! # Laravel for Rust
2//!
3//! A full-stack web framework for Rust.
4//!
5//! Most web applications need the same things: routing, validation, sessions, a database,
6//! queues, mail, and tests that exercise them. Laravel provides them in one crate,
7//! configured from the environment. This application serves a home page and a form handler
8//! that redirects back to it:
9//!
10//! ```no_run
11//! use std::process::ExitCode;
12//!
13//! use laravel::prelude::*;
14//!
15//! async fn home() -> &'static str {
16//!     "Welcome to Laravel for Rust"
17//! }
18//!
19//! #[derive(serde::Deserialize)]
20//! struct Profile {
21//!     name: Option<String>,
22//! }
23//!
24//! async fn store(request: Request) -> laravel::Result<Redirect> {
25//!     let name = request.parse::<Profile>()?.name.or_abort(422)?;
26//!     // ...
27//!     Ok(Redirect::route(home, ()))
28//! }
29//!
30//! fn web(route: &mut Router) {
31//!     route.get("/", home);
32//!     route.post("/users", store);
33//! }
34//!
35//! fn main() -> ExitCode {
36//!     Application::configure()
37//!         .with_routing(|routing, _| {
38//!             routing.web(web);
39//!         })
40//!         .run()
41//! }
42//! ```
43//!
44//! An application starts with [`Application`], and the [`prelude`] imports the types and
45//! traits most handlers use. The
46//! [documentation](https://github.com/laravel/rust-framework/blob/0.x/docs/installation.md)
47//! has a guide for each feature.
48//!
49//! Laravel is built on [Axum](https://docs.rs/axum). Handlers are Axum handlers, and any
50//! Axum extractor or tower layer works. The crate re-exports [`axum`] for applications that need
51//! to use Axum directly.
52//!
53//! # Features
54//!
55//! | Feature | Enables |
56//! | --- | --- |
57//! | `inertia` (default) | [Inertia](https://inertiajs.com) pages, in `laravel::inertia` |
58//! | `minijinja` (default) | `.html` views in Jinja's syntax, rendered by MiniJinja |
59//! | `database-sqlite`, `database-postgres`, `database-mysql` | Database connections for each driver, in `laravel::db`, and models in `laravel::model` |
60//! | `redis` | Redis connections, in `laravel::redis`, and the `redis` cache store, session driver, and queue driver |
61//! | `s3` | S3-compatible file storage |
62//! | `sqs` | The `sqs` and `cloud` queue drivers |
63//! | `ses` | The `ses` mail transport |
64//! | `opentelemetry` | Trace export over OTLP, configured by the `OTEL_*` variables |
65//! | `reverb` | The `reverb:start` command, which runs a Reverb server for local development |
66//! | `search` | Full-text search over models, in `laravel::search`. It needs a database driver feature too |
67//!
68//! Enabling `database` without a driver feature is a compile error, so enable a driver feature
69//! instead.
70
71#![warn(missing_docs)]
72
73extern crate self as laravel;
74
75#[cfg(all(
76    feature = "database",
77    not(any(
78        feature = "database-sqlite",
79        feature = "database-postgres",
80        feature = "database-mysql"
81    ))
82))]
83compile_error!("enable a database driver feature: `database-sqlite`, `database-postgres` or `database-mysql`");
84
85pub mod auth;
86pub mod broadcast;
87pub mod cache;
88pub mod config;
89pub mod console;
90pub mod container;
91pub mod context;
92pub mod cookie;
93pub mod crypt;
94#[cfg(feature = "database")]
95pub mod db;
96pub mod embed;
97pub mod errors;
98pub mod event;
99pub mod feature;
100pub mod foundation;
101pub mod hash;
102pub mod head;
103pub mod http;
104#[cfg(feature = "inertia")]
105pub mod inertia;
106pub mod lottery;
107pub mod mail;
108#[cfg(feature = "database")]
109pub mod model;
110pub mod notification;
111pub mod numeric;
112pub mod pagination;
113pub mod prelude;
114pub mod process;
115pub mod queue;
116pub mod rate_limit;
117#[cfg(feature = "redis")]
118pub mod redis;
119pub mod routing;
120pub mod schedule;
121#[cfg(feature = "search")]
122pub mod search;
123pub mod session;
124pub mod slack;
125pub mod sms;
126pub mod storage;
127pub mod str;
128pub mod stream;
129pub mod task;
130pub mod testing;
131pub mod time;
132pub mod url;
133pub mod validation;
134pub mod view;
135pub mod workflow;
136
137#[cfg(test)]
138mod tests;
139
140pub use axum;
141#[doc(hidden)]
142pub use laravel_core::__inventory;
143pub(crate) use laravel_core::*;
144
145pub use crate::config::config;
146#[doc(inline)]
147pub use laravel_core::{
148    Error, ErrorContext, OrAbort, Result, abort, abort_if, abort_unless, abort_with, now, once, once_for, report,
149    resolve,
150};
151#[cfg(feature = "database")]
152#[doc(hidden)]
153pub use laravel_database::{__column_names, __db_values, __model_joined};
154#[doc(hidden)]
155pub use laravel_http::{__invalid, __view_data};
156/// Embed a directory's files in the binary as an [`Embedded`](embed::Embedded).
157///
158/// The path is relative to the crate's `Cargo.toml`, as in `laravel::embed!("resources/views")`.
159pub use laravel_rust_macros::embed;
160
161/// Run a synchronous or asynchronous unit test, or an application test.
162///
163/// A test with no arguments runs without an application. A test that takes an
164/// `Application` argument gets a new application, booted, and its helpers run in
165/// that application's scope. The application comes from `app::testing::create`
166/// by default. To use another factory, write `#[laravel::test(app = path::to::factory)]`. A test
167/// that names a factory runs in its application's scope even without the argument, so it may leave
168/// the argument out when it only calls functions such as `laravel::config()`.
169///
170/// Async tests run on a current-thread Tokio runtime. Return values and attributes
171/// such as `#[should_panic]` and `#[ignore]` work as they do in ordinary Rust tests.
172///
173/// ```
174/// #[laravel::test]
175/// fn arithmetic() {
176///     assert_eq!(2 + 2, 4);
177/// }
178///
179/// #[laravel::test]
180/// async fn asynchronous_work() -> laravel::Result<()> {
181///     Ok(())
182/// }
183/// ```
184///
185/// ```no_run
186/// use laravel::Application;
187/// use laravel::testing::MakesHttpRequests;
188/// # fn create() -> Application { Application::configure().create() }
189///
190/// #[laravel::test(app = create)]
191/// async fn health_check(app: Application) {
192///     app.get("/up").await.assert_ok();
193/// }
194/// ```
195///
196/// ```compile_fail
197/// #[laravel::test]
198/// async fn too_many_arguments(a: laravel::Application, b: laravel::Application) {}
199/// ```
200pub use laravel_rust_macros::test;
201
202/// Declare a struct that a request fills.
203///
204/// The struct derives `Deserialize` and [`Validate`](crate::validation::Validate). With
205/// `fills = Model`, it also derives [`Fill`](crate::model::Fill) with `#[fills(Model)]`. Each
206/// [`Sometimes`](crate::validation::Sometimes) field gets `#[serde(default)]`, so deserializers
207/// outside the framework, such as `serde_json`, also decode a missing field as `Missing`. The
208/// struct's other attributes stay as written.
209///
210/// ```
211/// use laravel::validation::{Sometimes, Valid};
212///
213/// #[laravel::input]
214/// #[validate(anyone)]
215/// pub struct EditProfile {
216///     #[validate(required, max_length = 255)]
217///     pub name: Sometimes<String>,
218///     #[validate(max_length = 1000)]
219///     pub bio: Sometimes<Option<String>>,
220/// }
221///
222/// async fn update(Valid(input): Valid<EditProfile>) -> &'static str {
223///     if input.bio.is_null() { "Removed the bio" } else { "Saved" }
224/// }
225///
226/// let input: EditProfile = serde_json::from_str(r#"{"bio": null}"#).unwrap();
227/// assert!(input.name.is_missing());
228/// assert!(input.bio.is_null());
229/// ```
230pub use laravel_rust_http_macros::input;
231
232/// Declare a struct that a request's query string fills.
233///
234/// The struct derives `Deserialize`, [`Validate`](crate::validation::Validate), and
235/// [`QueryInput`](crate::http::QueryInput), so handlers may extract it with
236/// [`Query<T>`](crate::http::Query) or read it with [`Request::query`](crate::http::Request::query).
237///
238/// Fields with a fallback (`Option<T>`, [`Sometimes<T>`](crate::validation::Sometimes),
239/// `#[default]`, `#[default = expr]`, or `#[serde(default)]`) are lenient: missing, blank
240/// (`?q=`), wrong-type (`?page=abc`), or rule-failing (`?page=0`) values fall back to `None`,
241/// `Missing`, or their default. Fields without a fallback are required and fail with `400 Bad
242/// Request` when missing or invalid.
243///
244/// ```
245/// use laravel::prelude::*;
246///
247/// #[laravel::query]
248/// pub struct Search {
249///     #[default]
250///     pub q: String,
251///     #[default = 1]
252///     #[validate(min_value = 1)]
253///     pub page: u32,
254///     pub tag: Option<String>,
255/// }
256///
257/// async fn index(Query(search): Query<Search>) -> String {
258///     format!("{} (page {})", search.q, search.page)
259/// }
260/// ```
261pub use laravel_rust_http_macros::query;
262
263/// Make a notification from the `impl` block that holds its `mail` and `sms` methods.
264///
265/// Importing `laravel::notification` brings in both this attribute and the module. The
266/// [`notification`](mod@notification) module documents the methods a notification may define.
267pub use laravel_rust_queue_macros::notification;
268
269pub use crate::foundation::Application;
270pub use crate::view::view;
271/// Remember an async function's result for the rest of the [context](crate::context::Context),
272/// keyed by its arguments.
273///
274/// A request is one context, and so are a command and each
275/// [`Application::scope`](crate::Application::scope). The attribute applies
276/// [`once`](fn@crate::once) to the whole function and keys it by its arguments, as
277/// [`once_for`] does. Later calls with equal arguments get a clone of the first call's result.
278/// Calls that run at the same time share one computation, even when one of them stops waiting.
279/// An error result is remembered too.
280///
281/// ```no_run
282/// # #[derive(Clone)] pub struct Team;
283/// # #[derive(Clone)] pub struct User;
284/// # pub struct Teams;
285/// # impl Teams { async fn current(&self) -> Option<Team> { None } }
286/// # pub struct Users;
287/// # impl Users { async fn find(&self, id: u64) -> Option<User> { None } }
288/// /// The signed-in user's team, looked up at most once per request.
289/// #[laravel::once]
290/// pub async fn current_team() -> laravel::Result<Option<Team>> {
291///     Ok(laravel::resolve::<Teams>().await?.current().await)
292/// }
293///
294/// /// A user by ID, looked up at most once per request for each ID.
295/// #[laravel::once]
296/// pub async fn find_user(id: u64) -> laravel::Result<Option<User>> {
297///     Ok(laravel::resolve::<Users>().await?.find(id).await)
298/// }
299/// ```
300///
301/// The function's arguments are its key, so they must be owned values that implement
302/// [`Hash`](std::hash::Hash), such as a `u64` or a `String`, and its result must be `Clone`.
303/// Return an `Arc` to avoid cloning large values. The function's future must be `Send`. The
304/// attribute doesn't support generic functions or methods that take `self`.
305///
306/// ```compile_fail
307/// #[laravel::once]
308/// async fn slug(title: &str) -> String {
309///     title.to_lowercase()
310/// }
311/// ```
312pub use laravel_rust_macros::once;
313
314/// The framework version.
315pub const VERSION: &str = env!("CARGO_PKG_VERSION");