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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
use std::sync::Mutex;

use laravel::config::database::ConnectionConfig;
use laravel::container::Inject;
use laravel::db::{self, Condition, Value};
use laravel::event::{Event, listener};
use laravel::model::{
    self, BelongsTo, Changes, Created, Deleted, Draft, Fill, FoundOrCreated, HasMany, Hooks, Updated, create, model,
    update,
};
use laravel::str::Str;
use laravel::testing::prelude::*;
use laravel::time::Timestamp;
use laravel::validation::Sometimes;

#[model(hooks)]
pub struct User {
    pub id: i64,
    pub name: String,
    pub email: String,
    #[default]
    pub votes: i64,
    pub kind: String,
    pub created_at: Timestamp,
    pub updated_at: Timestamp,
    #[has_many]
    pub articles: HasMany<Article>,
}

impl Hooks for User {
    async fn updating(&mut self, _changes: &Changes<Self>) -> laravel::Result<()> {
        self.votes = self.votes.min(1000);
        Ok(())
    }
}

impl User {
    pub fn popular() -> Condition {
        User::votes.gt(100)
    }

    pub fn of_type(kind: &str) -> Condition {
        User::kind.eq(kind)
    }
}

#[derive(Fill)]
#[fills(User)]
pub struct NewUser {
    pub name: String,
    pub email: String,
    pub kind: String,
}

#[derive(Fill)]
#[fills(User)]
pub struct Rename {
    pub name: String,
}

#[derive(Fill)]
#[fills(User)]
pub struct SignUp {
    pub name: String,
    pub email: String,
    pub kind: String,
    #[fill(skip)]
    pub newsletter: bool,
}

#[derive(Fill)]
#[fills(User)]
pub struct Invite {
    pub name: String,
    pub email: Sometimes<String>,
    pub kind: String,
    #[fill(skip)]
    pub team_ids: Vec<i64>,
}

#[model(hooks)]
pub struct Article {
    pub id: i64,
    pub user_id: i64,
    pub title: String,
    pub slug: String,
    pub locked: bool,
    pub archived: bool,
    #[belongs_to]
    pub user: BelongsTo<User>,
}

#[derive(Fill)]
#[fills(Article)]
pub struct NewArticle {
    pub title: String,
    pub locked: bool,
    pub archived: bool,
}

impl Hooks for Article {
    async fn creating(article: &mut Draft<Self>) -> laravel::Result<()> {
        record("create".to_owned()).await?;
        let title = article.get(Article::title).cloned().unwrap_or_default();
        let author = article.get(Article::user_id).copied().unwrap_or_default();
        article.set(Article::slug, slug(author, &title)?);
        Ok(())
    }

    async fn updating(&mut self, changes: &Changes<Self>) -> laravel::Result<()> {
        let columns: Vec<&str> = changes.iter().map(|change| change.column).collect();
        record(format!("update {columns:?}")).await?;
        if changes.has(Article::locked) && !self.locked {
            self.locked = true;
        }
        if changes.has(Article::title) {
            self.title = self.title.trim().to_owned();
            self.slug = slug(self.user_id, &self.title)?;
        }
        Ok(())
    }

    async fn deleting(&self) -> laravel::Result<()> {
        laravel::abort_if(self.locked, 409)
    }
}

async fn record(write: String) -> laravel::Result<()> {
    laravel::resolve::<Recorded>().await?.hooks.lock().unwrap().push(write);
    Ok(())
}

fn slug(author: i64, title: &str) -> laravel::Result<String> {
    if title == "Forbidden" {
        return Err(laravel::abort_with(422, "That title is forbidden."));
    }
    Ok(format!("{author}-{}", title.slug()))
}

#[model]
pub struct Member {
    pub id: i64,
    pub name: String,
}

#[model(hooks)]
#[derive(PartialEq)]
pub struct Subscriber {
    pub id: i64,
    pub name: String,
    pub email: String,
}

impl Hooks for Subscriber {
    /// Insert the winner's row before any other create's insert, as a concurrent request would.
    async fn creating(subscriber: &mut Draft<Self>) -> laravel::Result<()> {
        if subscriber.get(Subscriber::name).is_some_and(|name| name != "Winner") {
            create!(Subscriber {
                name: "Winner",
                email: "taylor@laravel.com",
            })
            .await?;
        }
        Ok(())
    }
}

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, db::Enum)]
#[serde(rename_all = "snake_case")]
pub enum Status {
    Open,
    Done,
}

#[model]
pub struct Task {
    pub id: i64,
    pub title: String,
    pub priority: i64,
    pub due_at: Option<Timestamp>,
    pub status: Status,
}

#[derive(Default)]
struct Recorded {
    events: Mutex<Vec<String>>,
    updates: Mutex<Vec<Updated<User>>>,
    hooks: Mutex<Vec<String>>,
    tasks: Mutex<Vec<Updated<Task>>>,
}

impl Recorded {
    fn push(&self, event: impl Into<String>) {
        self.events.lock().unwrap().push(event.into());
    }

    fn events(&self) -> Vec<String> {
        self.events.lock().unwrap().clone()
    }

    fn take(&self) -> Vec<String> {
        std::mem::take(&mut self.events.lock().unwrap())
    }
}

#[listener(at_dispatch)]
async fn greet_member(event: Event<Created<Member>>, recorded: Inject<Recorded>) {
    recorded.push(format!("created {}", event.model.name));
}

#[listener]
async fn welcome_member(event: Event<Created<Member>>, recorded: Inject<Recorded>) {
    recorded.push(format!("welcome {}", event.model.name));
}

fn connection() -> ConnectionConfig {
    let mut connection = ConnectionConfig::new("sqlite::memory:");
    connection.max_connections = 1;
    connection
}

fn configure() -> laravel::foundation::ApplicationBuilder {
    Application::configure()
        .for_testing(env!("CARGO_MANIFEST_DIR"))
        .with_config(|config, _| {
            config.database.default = "app".into();
            config.database.add_connection("app", connection());
        })
        .with_services(|app| {
            app.instance(Recorded::default());
        })
}

fn app() -> Application {
    configure()
        .with_events(|events, _| {
            events.listen(|event: Event<Created<User>>, recorded: Inject<Recorded>| async move {
                recorded.push(format!("created {}", event.model.name));
            });
            events.listen(|event: Event<Updated<User>>, recorded: Inject<Recorded>| async move {
                let columns: Vec<&str> = event.changes.iter().map(|change| change.column).collect();
                recorded.push(format!("updated {} {columns:?}", event.model.name));
                recorded.updates.lock().unwrap().push((*event).clone());
            });
            events.listen(|event: Event<Updated<Task>>, recorded: Inject<Recorded>| async move {
                recorded.tasks.lock().unwrap().push((*event).clone());
            });
            events.listen(|event: Event<Deleted<User>>, recorded: Inject<Recorded>| async move {
                recorded.push(format!("deleted {}", event.model.name));
            });
            events.listen(
                |event: Event<Created<Article>>, recorded: Inject<Recorded>| async move {
                    recorded.push(format!("created {}", event.model.slug));
                },
            );
            events.listen(
                |event: Event<Updated<Article>>, recorded: Inject<Recorded>| async move {
                    recorded.push(format!("updated {}", event.model.slug));
                },
            );
            events.listen(
                |event: Event<Deleted<Article>>, recorded: Inject<Recorded>| async move {
                    recorded.push(format!("deleted {}", event.model.slug));
                },
            );
        })
        .create()
}

async fn create_tables() -> laravel::Result<()> {
    let connection = db::default_connection()?;
    connection
        .schema()
        .create("users", |table| {
            table.id();
            table.string("name");
            table.string("email").unique();
            table.big_integer("votes").default(0);
            table.string("kind");
            table.timestamps();
        })
        .await?;
    connection
        .schema()
        .create("articles", |table| {
            table.id();
            table.big_integer("user_id");
            table.string("title");
            table.string("slug");
            table.boolean("locked");
            table.boolean("archived");
        })
        .await?;
    connection
        .schema()
        .create("tasks", |table| {
            table.id();
            table.string("title");
            table.big_integer("priority");
            table.timestamp("due_at").nullable();
            table.string("status");
        })
        .await?;
    connection
        .schema()
        .create("members", |table| {
            table.id();
            table.string("name");
        })
        .await?;
    connection
        .schema()
        .create("subscribers", |table| {
            table.id();
            table.string("name");
            table.string("email").unique();
        })
        .await?;

    Ok(())
}

fn new_user(name: &str) -> NewUser {
    NewUser {
        name: name.into(),
        email: format!("{}@laravel.com", name.to_lowercase()),
        kind: "member".into(),
    }
}

fn new_article(title: &str) -> NewArticle {
    NewArticle {
        title: title.into(),
        locked: false,
        archived: false,
    }
}

fn value(value: impl Into<Value<'static>>) -> Value<'static> {
    value.into()
}

fn at(time: &str) -> Timestamp {
    time.parse().unwrap()
}

#[tokio::test]
async fn each_write_dispatches_its_event_once_with_the_model() -> laravel::Result<()> {
    let app = app();
    let recorded = app.resolve::<Recorded>().await;
    app.travel_to(at("2026-11-03T09:00:00Z"));

    app.scope(async || {
        create_tables().await?;
        let mut taylor = create!(User { ..new_user("Taylor") }).await?;
        assert_eq!(recorded.take(), ["created Taylor"]);

        app.travel_to(at("2026-11-03T10:00:00Z"));
        update!(taylor { name: "Otwell" }).await?;
        assert_eq!(recorded.take(), [r#"updated Otwell ["name", "updated_at"]"#]);
        let update = recorded.updates.lock().unwrap().remove(0);
        assert!(update.changes.has(User::name));
        assert!(update.changes.has(User::updated_at));
        assert!(!update.changes.has(User::email));
        assert!(!update.changes.has(User::votes));
        assert_eq!(update.changes.old(User::name), "Taylor");
        assert_eq!(update.changes.new(User::name), "Otwell");
        assert_eq!(update.changes.old(User::email), "taylor@laravel.com");
        assert_eq!(update.changes.new(User::email), "taylor@laravel.com");
        assert_eq!(update.model.name, "Otwell");
        assert_eq!(update.model.updated_at, at("2026-11-03T10:00:00Z"));

        update!(taylor { name: "Otwell" }).await?;
        update!(taylor { votes: taylor.votes }).await?;
        assert_eq!(recorded.take(), Vec::<String>::new(), "nothing changed");

        taylor.increment(User::votes, 5).await?;
        assert_eq!(
            recorded.take(),
            [r#"updated Otwell ["votes"]"#],
            "`updated_at` already holds the time"
        );
        let update = recorded.updates.lock().unwrap().remove(0);
        assert_eq!(*update.changes.old(User::votes), 0);
        assert_eq!(*update.changes.new(User::votes), 5);
        assert_eq!(User::find_or_fail(taylor.id).await?.votes, 5);
        taylor.increment(User::votes, 5000).await?;
        assert_eq!(taylor.votes, 1000);
        assert_eq!(
            User::find_or_fail(taylor.id).await?.votes,
            1000,
            "the `updating` hook's value replaces the increment"
        );
        recorded.take();
        recorded.updates.lock().unwrap().clear();

        taylor.delete().await?;
        assert_eq!(recorded.take(), ["deleted Otwell"]);

        create!(User { ..new_user("Abigail") }).await?;
        create!(User { ..new_user("James") }).await?;
        recorded.take();
        assert_eq!(User::destroy([2, 3, 4]).await?, 2);
        assert_eq!(recorded.take(), ["deleted Abigail", "deleted James"]);

        Ok(())
    })
    .await
}

#[tokio::test]
async fn changes_read_typed_values_from_before_and_after_the_update() -> laravel::Result<()> {
    let app = app();
    let recorded = app.resolve::<Recorded>().await;

    app.scope(async || {
        create_tables().await?;
        let mut task = create!(Task {
            title: "Write docs",
            priority: 1,
            status: Status::Open
        })
        .await?;
        update!(task {
            title: "Ship docs",
            priority: 3,
            due_at: at("2026-11-04T17:00:00Z"),
            status: Status::Done,
        })
        .await?;

        let update = recorded.tasks.lock().unwrap().remove(0);
        let changes = &update.changes;
        assert_eq!(
            (changes.old(Task::title).as_str(), changes.new(Task::title).as_str()),
            ("Write docs", "Ship docs")
        );
        assert_eq!((*changes.old(Task::priority), *changes.new(Task::priority)), (1, 3));
        assert_eq!(
            (*changes.old(Task::due_at), *changes.new(Task::due_at)),
            (None, Some(at("2026-11-04T17:00:00Z")))
        );
        assert_eq!(
            (changes.old(Task::status), changes.new(Task::status)),
            (&Status::Open, &Status::Done)
        );
        assert_eq!(
            changes
                .iter()
                .map(|change| (change.column, change.new.clone()))
                .collect::<Vec<_>>(),
            [
                ("title", value("Ship docs")),
                ("priority", value(3_i64)),
                ("due_at", value(at("2026-11-04T17:00:00Z"))),
                ("status", value("done")),
            ]
        );

        update!(task { priority: 2 }).await?;
        let update = recorded.tasks.lock().unwrap().remove(0);
        assert!(!update.changes.has(Task::title));
        assert_eq!(
            update.changes.old(Task::title),
            "Ship docs",
            "an unchanged column reads the same before and after"
        );
        assert_eq!(update.changes.new(Task::title), "Ship docs");

        Ok(())
    })
    .await
}

#[tokio::test]
async fn creating_functions_dispatch_created_only_when_they_insert() -> laravel::Result<()> {
    let app = app();
    let recorded = app.resolve::<Recorded>().await;
    app.travel_to(at("2026-11-03T09:00:00Z"));

    app.scope(async || {
        create_tables().await?;
        let taylor = User::first_or_create(User::email.eq("taylor@laravel.com"), new_user("Taylor"))
            .found_or_created()
            .await?;
        assert!(taylor.was_created());
        let taylor = taylor.into_model();
        let found = User::first_or_create(User::email.eq("taylor@laravel.com"), new_user("Taylor"))
            .found_or_created()
            .await?;
        assert!(matches!(&found, FoundOrCreated::Found(user) if user.is(&taylor)));
        assert_eq!(recorded.take(), ["created Taylor"]);

        let james = User::update_or_create(User::email.eq("james@laravel.com"), new_user("James"))
            .found_or_created()
            .await?;
        assert!(james.was_created());
        let mut renamed = new_user("James");
        renamed.kind = "admin".into();
        let updated = User::update_or_create(User::email.eq("james@laravel.com"), renamed)
            .found_or_created()
            .await?;
        assert!(matches!(&updated, FoundOrCreated::Found(user) if user.kind == "admin"));
        assert_eq!(recorded.take(), ["created James", r#"updated James ["kind"]"#]);

        let article = taylor.articles().create().fill(new_article("Hello World")).await?;
        taylor.articles().create_many([new_article("Second")]).await?;
        assert_eq!(recorded.take(), ["created 1-hello-world", "created 1-second"]);
        assert_eq!(article.user_id, taylor.id);

        Ok(())
    })
    .await
}

#[tokio::test]
async fn find_or_create_functions_return_a_row_inserted_after_their_lookup() -> laravel::Result<()> {
    let app = app();

    app.scope(async || {
        create_tables().await?;
        let email = "taylor@laravel.com";
        let found = Subscriber::first_or_create(Subscriber::email.eq(email), create!(Subscriber { name: "Late", .. }))
            .found_or_created()
            .await?;
        assert!(!found.was_created(), "another request created the row");
        let found = found.into_model();
        assert_eq!(Subscriber::query().get().await?, std::slice::from_ref(&found));
        assert_eq!(found.name, "Winner");

        Subscriber::query().delete().await?;
        let updated =
            Subscriber::update_or_create(Subscriber::email.eq(email), create!(Subscriber { name: "Late", .. }))
                .found_or_created()
                .await?;
        assert!(!updated.was_created(), "another request created the row");
        let updated = updated.into_model();
        assert_eq!(Subscriber::query().get().await?, std::slice::from_ref(&updated));
        assert_eq!(updated.name, "Late", "the values update the row that won");

        Ok(())
    })
    .await
}

#[tokio::test]
async fn query_writes_dispatch_no_events() -> laravel::Result<()> {
    let app = app();
    let recorded = app.resolve::<Recorded>().await;

    app.scope(async || {
        create_tables().await?;
        User::insert([new_user("Taylor")]).await?;
        User::upsert([new_user("Abigail"), new_user("Taylor")], [User::email], [User::name]).await?;
        update!(User::query().filter(User::name.eq("Taylor")) { votes += 1 }).await?;
        User::query().filter(User::name.eq("Abigail")).delete().await?;

        assert_eq!(User::query().count().await?, 1);
        assert_eq!(recorded.events(), Vec::<String>::new());

        Ok(())
    })
    .await
}

#[tokio::test]
async fn listeners_wait_for_the_transaction_and_skip_rollbacks_unless_they_run_in_it() -> laravel::Result<()> {
    let app = configure()
        .with_events(|events, _| {
            events.discover(env!("CARGO_CRATE_NAME"));
        })
        .create();
    let recorded = app.resolve::<Recorded>().await;

    app.scope(async || {
        create_tables().await?;
        db::transaction(async |_| {
            create!(Member { name: "Ada" }).await?;
            assert_eq!(recorded.events(), ["created Ada"]);
            Ok(())
        })
        .await?;
        assert_eq!(recorded.take(), ["created Ada", "welcome Ada"]);

        let rolled_back = db::transaction(async |_| {
            create!(Member { name: "Grace" }).await?;
            Err::<(), _>(laravel::abort_with(409, "Rolled back."))
        })
        .await;
        assert!(rolled_back.is_err());
        assert_eq!(recorded.take(), ["created Grace"]);
        assert_eq!(Member::query().count().await?, 1);

        Ok(())
    })
    .await
}

#[tokio::test]
async fn creating_and_updating_set_columns_that_the_write_stores() -> laravel::Result<()> {
    let app = app();
    let recorded = app.resolve::<Recorded>().await;
    let hooks = || std::mem::take(&mut *recorded.hooks.lock().unwrap());

    app.scope(async || {
        create_tables().await?;
        let taylor = create!(User { ..new_user("Taylor") }).await?;
        let mut article = taylor.articles().create().fill(new_article("Hello World")).await?;
        assert_eq!(article.slug, "1-hello-world");
        assert_eq!(Article::find_or_fail(article.id).await?.slug, "1-hello-world");
        assert_eq!(hooks(), ["create"]);

        recorded.take();
        update!(article { archived: true }).await?;
        assert_eq!(article.slug, "1-hello-world");
        assert_eq!(hooks(), [r#"update ["archived"]"#]);

        update!(article {
            title: "  Second Draft "
        })
        .await?;
        assert_eq!(article.title, "Second Draft", "`updating` changes what's written");
        assert_eq!(article.slug, "1-second-draft");
        let stored = Article::query().find_or_fail(article.id).await?;
        assert_eq!(
            (stored.title.as_str(), stored.slug.as_str()),
            ("Second Draft", "1-second-draft")
        );
        assert_eq!(hooks(), [r#"update ["title"]"#]);
        assert_eq!(recorded.take(), ["updated 1-hello-world", "updated 1-second-draft"]);

        update!(article { locked: true }).await?;
        update!(article { locked: false }).await?;
        assert!(article.locked, "`updating` set the column back, so nothing changed");
        assert_eq!(hooks(), [r#"update ["locked"]"#, r#"update ["locked"]"#]);
        assert_eq!(
            recorded.take(),
            ["updated 1-second-draft"],
            "the undone update dispatches nothing"
        );
        let stored = Article::query().find_or_fail(article.id).await?;
        assert!(stored.locked);

        update!(article { archived: true }).await?;
        assert_eq!(
            hooks(),
            Vec::<String>::new(),
            "an update that changes nothing runs no hook"
        );

        Ok(())
    })
    .await
}

#[tokio::test]
async fn a_hook_error_stops_the_write_and_reaches_the_caller() -> laravel::Result<()> {
    let app = app();
    let recorded = app.resolve::<Recorded>().await;

    app.scope(async || {
        create_tables().await?;
        let taylor = create!(User { ..new_user("Taylor") }).await?;
        recorded.take();

        let error = taylor
            .articles()
            .create()
            .fill(new_article("Forbidden"))
            .await
            .unwrap_err();
        assert_eq!(error.status(), 422);
        assert_eq!(error.to_string(), "That title is forbidden.");
        assert_eq!(Article::query().count().await?, 0);

        let mut article = taylor.articles().create().fill(new_article("Hello")).await?;
        let error = update!(article { title: "Forbidden" }).await.unwrap_err();
        assert_eq!(error.status(), 422);
        assert_eq!(Article::find_or_fail(article.id).await?.title, "Hello");

        let mut locked = new_article("Locked");
        locked.locked = true;
        let locked = create!(taylor.articles() { ..locked }).await?;
        let id = locked.id;
        assert_eq!(locked.delete().await.unwrap_err().status(), 409);
        assert_eq!(Article::destroy([id]).await.unwrap_err().status(), 409);
        assert!(Article::find(id).await?.is_some());
        assert_eq!(recorded.take(), ["created 1-hello", "created 1-locked"]);

        Ok(())
    })
    .await
}

#[tokio::test]
async fn without_events_mutes_events_but_runs_hooks() -> laravel::Result<()> {
    let app = app();
    let recorded = app.resolve::<Recorded>().await;

    app.scope(async || {
        create_tables().await?;
        let article = model::without_events(async {
            let mut taylor = create!(User { ..new_user("Taylor") }).await?;
            update!(taylor { name: "Otwell" }).await?;
            let article = taylor.articles().create().fill(new_article("Muted")).await?;
            create!(User { ..new_user("Abigail") }).await?.delete().await?;
            Ok::<_, laravel::Error>(article)
        })
        .await?;
        assert_eq!(article.slug, "1-muted");
        assert_eq!(recorded.events(), Vec::<String>::new());

        create!(User { ..new_user("James") }).await?;
        assert_eq!(recorded.events(), ["created James"]);

        Ok(())
    })
    .await
}

#[tokio::test]
async fn quietly_mutes_events_but_runs_hooks() -> laravel::Result<()> {
    let app = app();
    let recorded = app.resolve::<Recorded>().await;
    let hooks = || std::mem::take(&mut *recorded.hooks.lock().unwrap());

    app.scope(async || {
        create_tables().await?;
        let mut taylor = create!(User { ..new_user("Taylor") }).quietly().await?;
        update!(taylor { name: "Otwell" }).quietly().await?;
        taylor.update().kind("admin").quietly().await?;
        taylor.increment(User::votes, 5000).quietly().await?;
        assert_eq!(taylor.votes, 1000, "`updating` still runs");
        let mut article = create!(taylor.articles() { ..new_article("Quiet") }).quietly().await?;
        assert_eq!(article.slug, "1-quiet", "`creating` still runs");
        update!(article { title: " Still quiet " }).quietly().await?;
        assert_eq!(article.slug, "1-still-quiet", "`updating` still runs");
        assert_eq!(hooks(), ["create", r#"update ["title"]"#]);
        article.delete_quietly().await?;
        let james = create!(User {
            articles: [Article {
                title: "One",
                locked: false,
                archived: false
            }],
            ..new_user("James")
        })
        .quietly()
        .await?;
        assert_eq!(james.articles().count().await?, 1);
        assert_eq!(recorded.take(), Vec::<String>::new(), "no write dispatched an event");

        let taylor = User::find_or_fail(taylor.id).await?;
        assert_eq!(
            (taylor.name.as_str(), taylor.kind.as_str(), taylor.votes),
            ("Otwell", "admin", 1000)
        );
        create!(User { ..new_user("Abigail") }).await?;
        assert_eq!(recorded.take(), ["created Abigail"]);

        Ok(())
    })
    .await
}

#[tokio::test]
async fn a_fill_struct_fills_from_a_reference_and_stays_usable() -> laravel::Result<()> {
    let app = app();

    app.scope(async || {
        create_tables().await?;
        let invite = Invite {
            name: "Taylor".into(),
            email: Sometimes::Present("taylor@laravel.com".into()),
            kind: "admin".into(),
            team_ids: vec![1, 2],
        };
        let mut user = create!(User { votes: 5, ..&invite }).await?;
        assert_eq!(invite.team_ids, [1, 2]);

        let edit = Invite {
            name: "Abigail".into(),
            email: Sometimes::Missing,
            kind: "member".into(),
            team_ids: vec![3],
        };
        update!(user { ..&edit }).await?;
        assert_eq!(edit.team_ids, [3]);

        let row = User::query().filter(User::id.eq(user.id)).first().await?.unwrap();
        assert_eq!(
            (row.name.as_str(), row.email.as_str(), row.kind.as_str(), row.votes),
            ("Abigail", "taylor@laravel.com", "member", 5),
            "the update skips the missing email"
        );

        let built = User::create().fill(&invite).email("james@laravel.com").await?;
        assert_eq!(
            (built.name.as_str(), built.email.as_str()),
            ("Taylor", "james@laravel.com")
        );

        Ok(())
    })
    .await
}

#[tokio::test]
async fn create_sets_columns_the_input_lacks() -> laravel::Result<()> {
    let app = app();
    let recorded = app.resolve::<Recorded>().await;

    app.scope(async || {
        create_tables().await?;
        let user = User::create()
            .fill(Rename { name: "Taylor".into() })
            .email("taylor@laravel.com")
            .kind("admin")
            .await?;
        assert_eq!(
            (user.email.as_str(), user.kind.as_str()),
            ("taylor@laravel.com", "admin")
        );
        assert_eq!(recorded.take(), ["created Taylor"]);

        let sign_up = SignUp {
            name: "James".into(),
            email: "james@laravel.com".into(),
            kind: "member".into(),
            newsletter: true,
        };
        assert!(sign_up.newsletter);
        let james = create!(User { ..sign_up }).await?;
        assert_eq!(james.name, "James", "a skipped field fills no column");

        let article = create!(user.articles() { title: "Final", ..new_article("Draft") }).await?;
        assert_eq!(
            (article.user_id, article.slug.as_str()),
            (user.id, "1-final"),
            "`creating` sees the listed title"
        );

        Ok(())
    })
    .await
}

#[tokio::test]
async fn local_scopes_combine_in_filters_and_relation_filters() -> laravel::Result<()> {
    let app = app();

    app.scope(async || {
        create_tables().await?;
        for (name, kind, votes) in [
            ("Taylor", "admin", 150),
            ("Abigail", "admin", 50),
            ("James", "member", 200),
        ] {
            let mut input = new_user(name);
            input.kind = kind.into();
            let user = create!(User { ..input }).await?;
            update!(User::query().filter(User::id.eq(user.id)) { votes }).await?;
            create!(user.articles() { ..new_article(name) }).await?;
        }

        let users = User::query()
            .filter(User::popular() & User::of_type("admin"))
            .get()
            .await?;
        assert_eq!(
            users.iter().map(|user| user.name.as_str()).collect::<Vec<_>>(),
            ["Taylor"]
        );
        let articles = Article::query()
            .has_where(Article::user, User::popular() & User::of_type("admin"))
            .get()
            .await?;
        assert_eq!(
            articles
                .iter()
                .map(|article| article.title.as_str())
                .collect::<Vec<_>>(),
            ["Taylor"]
        );

        Ok(())
    })
    .await
}

#[tokio::test]
async fn creating_reads_the_columns_that_a_find_or_create_condition_sets() -> laravel::Result<()> {
    app()
        .scope(async || {
            create_tables().await?;
            let taylor = create!(User { ..new_user("Taylor") }).await?;
            let condition = || Article::title.eq("Hello World") & Article::user_id.eq(taylor.id);
            let values = || Article::create().locked(false).archived(false);

            let created = Article::first_or_create(condition(), values()).await?;
            let found = Article::first_or_create(condition(), values()).await?;
            let other =
                Article::first_or_create(Article::title.eq("Second") & Article::user_id.eq(taylor.id), values())
                    .await?;

            assert_eq!(created.slug, "1-hello-world");
            assert_eq!(found.id, created.id);
            assert_eq!(other.slug, "1-second");
            Ok(())
        })
        .await
}