use laravel::auth::{Authenticatable, UserProvider};
use laravel::config::database::ConnectionConfig;
use laravel::db::{self, col, sqlx::AssertSqlSafe};
use laravel::hash::PasswordHash;
use laravel::http::{Json, Request};
use laravel::model::model;
use laravel::routing::Params;
use laravel::testing::prelude::*;
use laravel::validation::{DatabaseRules, Rule, Rules, Valid, Validate, ValidationError};
use serde::Deserialize;
use serde_json::{Value, json};
use crate::support::Invalid;
#[derive(Clone, db::FromRow)]
struct User {
id: i64,
}
impl Authenticatable for User {
type Id = i64;
fn auth_id(&self) -> i64 {
self.id
}
fn auth_password(&self) -> Option<&PasswordHash> {
None
}
fn remember_token(&self) -> Option<&str> {
None
}
}
struct Users;
impl UserProvider for Users {
type User = User;
async fn find(&self, id: &i64) -> laravel::Result<Option<User>> {
db::query!("SELECT id FROM users WHERE id = {id}").select_one_as().await
}
async fn find_for_login(&self, _: &str) -> laravel::Result<Option<User>> {
Ok(None)
}
async fn update_password(&self, _: &User, _: &PasswordHash) -> laravel::Result<()> {
Ok(())
}
async fn update_remember_token(&self, _: &User, _: &str) -> laravel::Result<()> {
Ok(())
}
}
#[model(route_key = "code")]
struct Project {
id: i64,
code: String,
}
#[model(route_key = "slug")]
struct Team {
id: i64,
name: Option<String>,
slug: String,
}
#[model]
struct Label {
id: i64,
project_id: i64,
}
#[derive(Deserialize, Validate)]
#[validate(anyone)]
struct LabelIssue {
#[validate(each(exists("labels", "id", filter = col("project_id").eq(route::<Project>("project")))))]
label_ids: Vec<i64>,
}
#[derive(Deserialize, Validate)]
#[validate(anyone)]
struct TagIssue {
#[validate(each(exists(Label::id, filter = Label::project_id.eq(route::<Project>("project")))))]
label_ids: Vec<i64>,
}
#[derive(Deserialize, Validate)]
#[validate(anyone)]
struct TeamSettings {
#[validate(required, unique(Team::name, ignore = route("team")))]
name: String,
}
#[derive(Deserialize, Validate)]
#[validate(anyone)]
struct Registration {
#[validate(required, email, unique("users"))]
email: String,
#[validate(required, exists("teams", "id"))]
team_id: i64,
#[validate(each(exists("tags", "id")))]
tag_ids: Vec<i64>,
#[validate(exists("users", "id"))]
#[expect(dead_code, reason = "only validated")]
owner_id: Option<u64>,
#[validate(exists("teams", "slug"))]
#[expect(dead_code, reason = "only validated")]
team_slug: Option<String>,
}
#[derive(Deserialize, Validate)]
#[validate(anyone)]
struct ForgotPassword {
#[validate(required, email, exists("users", "email"))]
email: String,
}
#[derive(Deserialize, Validate)]
#[validate(anyone)]
struct Profile {
#[validate(required, unique("users", ignore = user))]
email: String,
}
#[derive(Deserialize, Validate)]
#[validate(anyone)]
struct JoinTeam {
#[validate(required, exists("teams", "id", filter = col("archived_at").is_null()))]
team_id: i64,
}
#[derive(Deserialize, Validate)]
#[validate(anyone)]
struct Invitation {
#[validate(required, email)]
email: String,
}
#[derive(Deserialize, Validate)]
#[validate(anyone)]
struct RenameTeam {
#[validate(required, max_length = 10)]
name: String,
}
async fn register(Valid(registration): Valid<Registration>) -> Json<Value> {
Json(json!({ "email": registration.email, "team_id": registration.team_id, "tag_ids": registration.tag_ids }))
}
async fn update_profile(Valid(profile): Valid<Profile>) -> String {
profile.email
}
async fn join_team(Valid(form): Valid<JoinTeam>) -> String {
form.team_id.to_string()
}
async fn invite(Params(team): Params<i64>, request: Request) -> laravel::Result<String> {
let form: Invitation = request
.validate_with(|rules| {
rules.field(
"email",
[Rule::unique_in::<String>("users", "email").filter(col("team_id").eq(team))],
)
})
.await?;
Ok(format!("{team}: {}", form.email))
}
async fn rename_team(Params(team): Params<i64>, request: Request) -> laravel::Result<String> {
let form: RenameTeam = request
.validate_with(|rules| rules.field("name", [Rule::unique_in::<String>("teams", "name").ignore(team)]))
.await?;
Ok(form.name)
}
fn application(connection: ConnectionConfig) -> Application {
Application::configure()
.for_testing(env!("CARGO_MANIFEST_DIR"))
.with_config(move |config, _| {
config.database.default = "primary".into();
config.database.add_connection("primary", connection);
})
.with_services(|app| {
app.instance(Users);
})
.with_auth(|auth, _| {
auth.session::<Users>();
})
.with_routing(|routing, _| {
routing.web(|route| {
route.post("/register", register);
route.put("/profile", update_profile);
route.post("/forgot-password", |Valid(form): Valid<ForgotPassword>| async move {
form.email
});
route.put("/teams/{team}/name", rename_team);
route.post("/teams/join", join_team);
route.post("/teams/{team}/invitations", invite);
route.post(
"/projects/{project}/labels",
|_: Project, Valid(form): Valid<LabelIssue>| async move { Json(form.label_ids) },
);
route.post("/projects/{project}/tags", |Valid(form): Valid<TagIssue>| async move {
Json(form.label_ids)
});
route.put(
"/teams/{team}/settings",
|team: Team, Valid(form): Valid<TeamSettings>| async move { format!("{}: {}", team.id, form.name) },
);
route.put("/teams/{team}/rename", |Valid(form): Valid<TeamSettings>| async move {
form.name
});
});
})
.create()
}
async fn seed(app: &Application) -> laravel::Result<()> {
app.scope(async || {
let connection = db::default_connection()?;
for sql in [
"DROP TABLE IF EXISTS users",
"DROP TABLE IF EXISTS teams",
"DROP TABLE IF EXISTS tags",
"DROP TABLE IF EXISTS projects",
"DROP TABLE IF EXISTS labels",
"CREATE TABLE projects (id BIGINT PRIMARY KEY, code VARCHAR(16) NOT NULL)",
"CREATE TABLE labels (id BIGINT PRIMARY KEY, project_id BIGINT NOT NULL)",
"INSERT INTO projects (id, code) VALUES (1, 'WEB'), (2, 'API')",
"INSERT INTO labels (id, project_id) VALUES (10, 1), (11, 1), (20, 2)",
"CREATE TABLE users (id BIGINT PRIMARY KEY, email VARCHAR(255) NOT NULL, team_id BIGINT)",
"CREATE TABLE teams (id BIGINT PRIMARY KEY, name VARCHAR(255), slug VARCHAR(255), archived_at VARCHAR(32))",
"CREATE TABLE tags (id BIGINT PRIMARY KEY)",
"INSERT INTO users (id, email, team_id) VALUES (1, 'taylor@example.com', 2), (2, 'jess@example.com', 3)",
"INSERT INTO teams (id, name, slug, archived_at) VALUES (2, 'Laravel', 'laravel', NULL), (3, 'Classic', 'classic', '2026-01-01')",
"INSERT INTO tags (id) VALUES (1), (3)",
] {
connection.query(AssertSqlSafe(sql)).statement().await?;
}
Ok(())
})
.await
}
async fn check_database_rules(app: Application) -> laravel::Result<()> {
seed(&app).await?;
let response = app
.post("/register")
.form(json!({ "email": "taylor@example.com", "team_id": "7", "tag_ids[0]": "1", "tag_ids[1]": "9" }))
.header("accept", "application/json")
.await;
response.assert_status(422);
assert_eq!(
response.json()["errors"],
json!({
"email": ["The email has already been taken."],
"team_id": ["The selected team id is invalid."],
"tag_ids.1": ["The selected tag_ids.1 is invalid."],
})
);
app.post("/register")
.form(json!({ "email": "dayle@example.com", "team_id": "2", "tag_ids[0]": "3", "tag_ids[1]": "1" }))
.await
.assert_ok()
.assert_exact_json(json!({ "email": "dayle@example.com", "team_id": 2, "tag_ids": [3, 1] }));
let response = app
.post("/register")
.json(json!({ "email": "dayle@example.com", "team_id": "two", "tag_ids": [] }))
.await;
response.assert_status(422);
assert_eq!(
response.json()["errors"],
json!({ "team_id": ["The team id field must be an integer."] }),
"a value that doesn't decode as the field's type isn't looked up"
);
let response = app.post("/forgot-password").json(json!({ "email": "taylor" })).await;
response.assert_status(422);
assert_eq!(
response.json()["errors"],
json!({ "email": ["The email field must be a valid email address."] }),
"a field that already failed a rule isn't looked up"
);
let register = |owner_id: u64, team_slug: &str| json!({ "email": "abigail@example.com", "team_id": 2, "tag_ids": [], "owner_id": owner_id, "team_slug": team_slug });
app.post("/register").json(register(1, "laravel")).await.assert_ok();
let nul_matches = app
.scope(async || match db::default_connection()?.driver() {
db::Driver::Postgres => Ok(false),
_ => {
db::table("teams")
.filter(db::col("slug").eq("lara\0vel"))
.exists()
.await
}
})
.await?;
let response = app.post("/register").json(register(u64::MAX, "lara\0vel")).await;
response.assert_status(422);
let mut errors = json!({ "owner_id": ["The selected owner id is invalid."] });
if !nul_matches {
errors["team_slug"] = json!(["The selected team slug is invalid."]);
}
assert_eq!(
response.json()["errors"],
errors,
"a value the database can't bind matches no row"
);
let taylor = User { id: 1 };
app.put("/profile")
.acting_as(&taylor)
.json(json!({ "email": "taylor@example.com" }))
.await
.assert_ok();
app.put("/profile")
.acting_as(&taylor)
.json(json!({ "email": "jess@example.com" }))
.await
.assert_status(422)
.assert_invalid_messages(&[("email", "The email has already been taken.")]);
app.put("/profile")
.json(json!({ "email": "taylor@example.com" }))
.await
.assert_status(422)
.assert_invalid(&["email"]);
app.post("/teams/join")
.json(json!({ "team_id": 2 }))
.await
.assert_ok()
.assert_see("2");
app.post("/teams/join")
.json(json!({ "team_id": 3 }))
.await
.assert_status(422)
.assert_invalid_messages(&[("team_id", "The selected team id is invalid.")]);
app.post("/teams/3/invitations")
.json(json!({ "email": "taylor@example.com" }))
.await
.assert_ok()
.assert_see("3: taylor@example.com");
app.post("/teams/2/invitations")
.json(json!({ "email": "taylor@example.com" }))
.await
.assert_status(422)
.assert_invalid_messages(&[("email", "The email has already been taken.")]);
app.post("/projects/WEB/labels")
.json(json!({ "label_ids": [10, 11] }))
.await
.assert_ok()
.assert_exact_json(json!([10, 11]));
app.post("/projects/WEB/labels")
.json(json!({ "label_ids": [10, 20] }))
.await
.assert_status(422)
.assert_invalid_messages(&[("label_ids.1", "The selected label_ids.1 is invalid.")]);
app.post("/projects/API/labels")
.json(json!({ "label_ids": [20] }))
.await
.assert_ok();
app.post("/projects/DOCS/labels")
.json(json!({ "label_ids": [10] }))
.await
.assert_not_found();
app.post("/projects/WEB/tags")
.json(json!({ "label_ids": [10, 20] }))
.await
.assert_status(422)
.assert_invalid_messages(&[("label_ids.1", "The selected label_ids.1 is invalid.")]);
app.post("/projects/API/tags")
.json(json!({ "label_ids": [20] }))
.await
.assert_ok();
app.put("/teams/laravel/settings")
.json(json!({ "name": "Laravel" }))
.await
.assert_ok()
.assert_see("2: Laravel");
app.put("/teams/laravel/rename")
.json(json!({ "name": "Laravel" }))
.await
.assert_ok()
.assert_see("Laravel");
app.put("/teams/classic/settings")
.json(json!({ "name": "Laravel" }))
.await
.assert_status(422)
.assert_invalid_messages(&[("name", "The name has already been taken.")]);
app.put("/teams/2/name")
.json(json!({ "name": "Laravel" }))
.await
.assert_ok()
.assert_see("Laravel");
let response = app.put("/teams/3/name").json(json!({ "name": "Laravel" })).await;
response.assert_status(422);
assert_eq!(
response.json()["errors"],
json!({ "name": ["The name has already been taken."] })
);
let response = app
.put("/teams/2/name")
.json(json!({ "name": "Laravel Labs Incorporated" }))
.await;
response.assert_status(422);
assert_eq!(
response.json()["errors"],
json!({ "name": ["The name field must not be greater than 10 characters."] }),
"the type's declared rules still run"
);
Ok(())
}
#[tokio::test]
async fn database_rules_look_up_submitted_values_as_the_fields_type() -> laravel::Result<()> {
let mut connection = ConnectionConfig::new("sqlite::memory:");
connection.max_connections = 1;
connection.idle_timeout = None;
connection.max_lifetime = None;
let app = application(connection);
check_database_rules(app.clone()).await?;
let input = serde_json::from_value(json!({ "name": "Laravel" }))?;
for rules in [
Rules::new().field(
"name",
(
Rule::required(),
Rule::unique_in::<String>("teams", "name").ignore(None::<i64>),
),
),
Rules::new().field(
"name",
[Rule::unique_in::<String>("teams", "name")
.ignore(None::<String>)
.ignore_column("archived_at")],
),
] {
assert!(
matches!(
app.scope(async || rules.validate(&input).await).await,
Err(ValidationError::Invalid(_))
),
"a null ID skips no row, including rows whose ignored column is null"
);
}
let rules = {
let slug = "laravel".to_owned();
Rules::new().field(
"name",
[Rule::unique_in::<String>("teams", "name")
.ignore(&slug)
.ignore_column("slug")],
)
};
app.scope(async || rules.validate(&input).await).await?;
let rules = {
let slug = "classic".to_owned();
Rules::new().field(
"name",
[Rule::unique_in::<String>("teams", "name")
.ignore(slug.as_str())
.ignore_column("slug")],
)
};
let error = app.scope(async || rules.validate(&input).await).await.unwrap_err();
assert_eq!(error.invalid().errors()["name"], ["The name has already been taken."]);
Ok(())
}
#[cfg(feature = "database-postgres")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_POSTGRES_URL pointing to a disposable database"]
async fn database_rules_bind_form_text_as_the_fields_type_on_postgres() -> laravel::Result<()> {
let url = std::env::var("LARAVEL_TEST_POSTGRES_URL").expect("LARAVEL_TEST_POSTGRES_URL");
let app = application(ConnectionConfig::new(url).initialize("SET search_path TO laravel_validation"));
app.scope(async || {
db::query!("CREATE SCHEMA IF NOT EXISTS laravel_validation")
.statement()
.await
})
.await?;
check_database_rules(app).await
}
#[cfg(feature = "database-mysql")]
#[tokio::test]
#[ignore = "requires LARAVEL_TEST_MYSQL_URL pointing to a disposable database"]
async fn database_rules_bind_form_text_as_the_fields_type_on_mysql() -> laravel::Result<()> {
let url = std::env::var("LARAVEL_TEST_MYSQL_URL").expect("LARAVEL_TEST_MYSQL_URL");
check_database_rules(application(ConnectionConfig::new(url))).await
}
#[tokio::test]
async fn misconfigured_database_rules_fail_validation_instead_of_rejecting_input() -> laravel::Result<()> {
let app = application(ConnectionConfig::new("sqlite::memory:"));
let input = serde_json::from_value(json!({ "email": "taylor@example.com" }))?;
for (rule, expected) in [
(
Rule::unique_in::<String>("users", "email").ignore_user(),
"the `unique` rule needs the request: validate with `Valid` or `request.validate()`",
),
(
Rule::unique_in::<String>("users; DROP TABLE users", "email"),
"`users; DROP TABLE users` isn't a table or column name for a database validation rule",
),
] {
let rules = Rules::new().field("email", [rule]);
let Err(ValidationError::Failed(error)) = app.scope(async || rules.validate(&input).await).await else {
panic!("validation should fail");
};
assert_eq!(error.status(), 500);
assert_eq!(error.to_string(), expected);
}
let (rule, built) = (Rule::exists_in::<String>("missing_table", "email"), line!());
for (rules, line) in [
(Rules::new().field("email", [rule]), built),
(<MissingTable as Validate>::declared_rules(), MISSING_TABLE_RULE),
] {
let Err(ValidationError::Failed(error)) = app.scope(async || rules.validate(&input).await).await else {
panic!("validation should fail");
};
let location = error.location().map(|location| (location.file(), location.line()));
assert_eq!(location, Some((file!(), line)), "a failed lookup points at the rule");
}
Ok(())
}
const MISSING_TABLE_RULE: u32 = line!() + 4;
#[derive(Deserialize, Validate)]
#[expect(dead_code, reason = "only validated")]
struct MissingTable {
#[validate(exists("missing_table", "email"))]
email: String,
}
#[model(connection = "directory")]
struct Region {
id: i64,
}
#[derive(Deserialize, Validate)]
#[expect(dead_code, reason = "only validated")]
struct Office {
#[validate(required, exists(Region::id))]
region_id: i64,
}
#[tokio::test]
async fn typed_database_rules_look_on_the_models_connection() -> laravel::Result<()> {
let sqlite = || {
let mut connection = ConnectionConfig::new("sqlite::memory:");
connection.max_connections = 1;
connection.idle_timeout = None;
connection.max_lifetime = None;
connection
};
let app = Application::configure()
.for_testing(env!("CARGO_MANIFEST_DIR"))
.with_config(move |config, _| {
config.database.default = "primary".into();
config.database.add_connection("primary", sqlite());
config.database.add_connection("directory", sqlite());
})
.create();
let rules = <Office as Validate>::declared_rules();
let known = serde_json::from_value(json!({ "region_id": 1 }))?;
let unknown = serde_json::from_value(json!({ "region_id": 2 }))?;
app.scope(async || {
let directory = db::connection("directory")?;
directory
.query(AssertSqlSafe("CREATE TABLE regions (id BIGINT PRIMARY KEY)"))
.statement()
.await?;
directory
.query(AssertSqlSafe("INSERT INTO regions (id) VALUES (1)"))
.statement()
.await
})
.await?;
assert!(app.scope(async || rules.validate(&known).await).await.is_ok());
assert!(matches!(
app.scope(async || rules.validate(&unknown).await).await,
Err(ValidationError::Invalid(_))
));
Ok(())
}