laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
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();
    // PostgreSQL can't bind NUL, and MySQL 8's default collation ignores it, so the rule follows the column's comparison...
    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");
    // A schema of its own, because other tests on the database make `users` and `teams` tables too...
    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(())
}