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 {
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
}