27 / 35

Data, Models & Forms· 13 min read· Lesson 27 of 35

Querying Models

Part 2 · Laravel Rust. Filter the café menu with compile-checked queries, combine conditions with & | !, see the safe SQL Laravel writes, and avoid the N+1 trap with eager loading.

Your models are ready, so it’s time to ask the database questions. Which drinks are available? Which orders are still waiting? In this lesson you’ll write queries: requests for exactly the rows you need. You’ll see how Laravel Rust checks them while compiling, what SQL it sends behind the scenes, and how to load related data without making your site crawl.

Your first queries

The simplest question is “give me everything”:

use crate::models::MenuItem;
let menu = MenuItem::all().await?;

all() returns a Vec<MenuItem>: every row in menu_items. That’s fine for a tiny menu, but usually you want some rows, in a certain order. For that, start a query with query() and finish it with get():

let menu = MenuItem::query()
.filter(MenuItem::available.eq(true))
.order_by(MenuItem::name)
.get()
.await?;
  1. MenuItem::query() starts building a query for the menu_items table. Nothing has run yet; you’re writing an order slip.
  2. .filter(...) adds a condition: only rows whose available column equals true.
  3. .order_by(MenuItem::name) sorts alphabetically by name.
  4. .get() says “that’s the whole slip”, and .await? hands it to the database and waits for the rows.

Here is the café menu handler, putting it together:

src/http/handlers/menu.rs
use laravel::prelude::*;
use crate::models::MenuItem;
pub async fn index() -> laravel::Result<Json<Vec<MenuItem>>> {
let menu = MenuItem::query()
.filter(MenuItem::available.eq(true))
.order_by(MenuItem::price_cents.asc())
.get()
.await?;
Ok(Json(menu))
}

This returns the available menu as JSON, cheapest first. .asc() and .desc() choose the sort direction.

Fetching one row

Often you want one specific row:

let espresso: Option<MenuItem> = MenuItem::find(1).await?;
let order = Order::find_or_fail(42).await?;
let latte = MenuItem::first_where(MenuItem::name.eq("Latte")).await?;
  1. find(1) looks up the row with primary key 1 and returns an Option, because it might not exist.
  2. find_or_fail(42) returns the model directly, or turns “not found” into a 404 response for you.
  3. first_where(...) returns the first row matching a condition, as an Option.

(Remember route model binding from Route Model Binding and URLs? It does this lookup for you when the id comes from the URL.)

If you read the id from the URL yourself, the docs use two types in different places. The routing guide parses a plain number with Params<u64> (a non-negative number that you might only display), while the models guide takes Params<i64> when the id goes straight into find_or_fail, so it matches the model’s i64 key without a conversion. For model lookups, use Params<i64>:

pub async fn show(Params(id): Params<i64>) -> laravel::Result<Json<Order>> {
let order = Order::find_or_fail(id).await?;
Ok(Json(order))
}

Either way, a URL like /orders/latte doesn’t parse as a number, so the request gets a 404 and your handler never runs.

Typed columns: the compiler checks your query

Look again at MenuItem::available and MenuItem::price_cents. These aren’t strings. #[model] generates a typed column for every field, and each one knows its Rust type.

That means:

  • A misspelled column such as MenuItem::prise_cents doesn’t exist, so the code doesn’t compile.
  • Comparing a number column with text, like MenuItem::price_cents.eq("cheap"), also fails to compile, because price_cents is an i64.

In many frameworks, those mistakes only show up when a customer clicks the page. Here, the compiler catches them first.

Typed columns come with comparison methods. The most useful ones:

Method Meaning
eq, ne equal, not equal
lt, le, gt, ge less than, at most, greater than, at least
is_in([...]) matches any value in a list
between(low, high) inside a range
is_null(), is_not_null() for Option columns
contains, starts_with, ends_with for text columns

Combining conditions with &, | and !

Real questions have several parts. “Show available items that cost at most $3.50, or anything in the pastry case.” Laravel Rust lets you combine conditions with the same symbols you’d use for booleans in Rust:

  • & means and: both must be true.
  • | means or: at least one must be true.
  • ! means not: flips a condition.
let picks = MenuItem::query()
.filter(
MenuItem::available.eq(true)
& (MenuItem::price_cents.le(350) | MenuItem::name.contains("Muffin")),
)
.get()
.await?;
  1. MenuItem::available.eq(true) must hold no matter what.
  2. The parentheses group the “or” part: cheap items or muffins.
  3. & joins them, so an unavailable muffin is still left out.

Use ! to negate a condition, for example .filter(!MenuItem::description.is_null()) for items that have a description. And calling .filter(...) several times means “and” between each call.

Tip

Just like in maths, parentheses matter. a & (b | c) and (a & b) | c ask different questions. Write the parentheses you mean, and Laravel keeps them in the SQL.

The SQL Laravel writes for you

Your Rust query becomes SQL before it reaches the database. For the query above, the WHERE part comes out roughly like this on PostgreSQL:

where "available" = $1 and ("price_cents" <= $2 or "name" like $3)

Two important things are happening:

  1. Parentheses are preserved. Laravel wraps your groups exactly as you wrote them, so “and” and “or” never get mixed up.
  2. Your values are not in the SQL text. You see $1, $2, $3 instead of true, 350 and '%Muffin%'. These are parameters (placeholders), and the real values travel to the database separately.

Why does that second point matter? It protects you from SQL injection, an attack where someone types SQL into a form, hoping it gets glued into your query. Because values never become part of the SQL text, there’s nothing for an attacker to glue into. You’ll look at injection closely in Raw Queries with db::query!.

Note

The exact SQL text differs between PostgreSQL, MySQL, MariaDB and SQLite (for example $1 versus ? placeholders). Laravel picks the right form for your database. See the Models guide (opens in new tab) for every filter method.

Other handy finishers

Instead of get(), you can end a query in other ways:

let waiting = Order::query()
.filter(Order::status.eq(OrderStatus::Pending))
.count()
.await?;
let names = MenuItem::query()
.order_by(MenuItem::name)
.pluck(MenuItem::name)
.await?;
let latest = Order::query()
.order_by(Order::created_at.desc())
.limit(10)
.get()
.await?;
  1. count() returns how many orders are pending, without loading them.
  2. pluck(MenuItem::name) returns just the names as a Vec<String>.
  3. limit(10) caps the result at ten rows: the ten newest orders.

Relationships and the N+1 problem

The café’s staff screen lists the last 25 orders with the customer’s account name. A first attempt might look like this:

Output
1 query: fetch the 25 latest orders
25 queries: for each order, fetch its user
-----------------------------------------
26 queries in total

This is the famous N+1 problem: one query for the list, plus one more query for each of the N rows. Imagine a waiter who walks to the kitchen, brings back one plate, then walks back for the next plate, 25 times. Each trip is quick, but together they make the page slow, and it gets worse as the café grows.

In many ORMs, this happens silently. You write order.user.name inside a loop, and the framework quietly runs a query each time. This is called lazy loading, and you often don’t notice until the site is slow.

Laravel Rust never lazy-loads behind your back. Instead, you say up front what you need, with with:

let orders = Order::query()
.with(Order::user)
.order_by(Order::created_at.desc())
.limit(25)
.get()
.await?;
for order in &orders {
println!("#{} for {}", order.id, order.user.name);
}
  1. .with(Order::user) asks Laravel to eager load the user relationship.
  2. Laravel runs the orders query, then one query fetching all the users those orders refer to, and fills in each order.user.
  3. Inside the loop, order.user.name is already in memory. No extra trips.

That’s 2 queries instead of 26: the waiter carries every plate on one tray.

Need more than one relationship? Pass a tuple. You can even load relationships of relationships:

let orders = Order::query()
.with((Order::user, Order::items.with(OrderItem::menu_item)))
.get()
.await?;

This loads each order’s user, its line items, and each line item’s menu item, one query per relationship.

Warning

If you forget with and read a relationship anyway, your app panics with a message like Order::items isn't loaded; add `.with(Order::items)` to the query. It sounds scary, but it’s helpful: the mistake shows up loudly while you develop, along with the exact fix, instead of quietly slowing down production.

Querying through a relationship

Sometimes you don’t want to load a relationship, you want to search it. Call the relationship as a method to get a query scoped to that parent:

let pending = user
.orders()
.filter(Order::status.eq(OrderStatus::Pending))
.get()
.await?;

user.orders() starts a query for only this user’s orders (this needs the #[has_many] orders field on User). If you already hold a model in a mut variable (say, one from route model binding), you can also load relationships afterwards with order.load(Order::items).await?.

Try it yourself

  1. Write a query for menu items that are available and cost between $2.00 and $4.00, sorted by price from highest to lowest.
  2. The kitchen screen shows every order that is Pending or Preparing, oldest first, with each order’s items and their menu items. Write the query with no N+1 problem.
Show solution
let mid_range = MenuItem::query()
.filter(MenuItem::available.eq(true) & MenuItem::price_cents.between(200, 400))
.order_by(MenuItem::price_cents.desc())
.get()
.await?;
let queue = Order::query()
.filter(
Order::status.eq(OrderStatus::Pending) | Order::status.eq(OrderStatus::Preparing),
)
.with(Order::items.with(OrderItem::menu_item))
.order_by(Order::created_at.asc())
.get()
.await?;

The | joins the two status checks. You could also write Order::status.is_in([OrderStatus::Pending, OrderStatus::Preparing]). The nested with loads items and their menu items in two extra queries in total, no matter how many orders there are.

Recap

  • Start with Model::query(), add .filter(...), .order_by(...) and .limit(...), and finish with .get(), .count(), .pluck(...) and friends.
  • Typed columns like MenuItem::price_cents make misspelled columns and wrong value types compile errors.
  • Combine conditions with & (and), | (or) and ! (not); Laravel keeps your parentheses in the SQL.
  • Values are sent as parameters, never pasted into the SQL text, which blocks SQL injection.
  • The N+1 problem is one query per row; Laravel never lazy-loads, so you eager load with with and get one query per relationship.

What’s next

So far, all the data came from you. Next, in Typed Validation and Forms, you’ll let customers place orders through a form, safely.

0 of 35 lessons complete

Search lessons

Type to search all lessons.