Accept a note only through a validated form

A StoreNote struct must declare who may submit it, and create! ignores fields the struct does not list.

The access course is still 0.x. A rule or attribute that stops compiling should be checked against the validation guide for your installed crate, not against PHP Laravel.

The validation guide’s rule is strict: every input struct needs #[validate(anyone)], #[validate(authenticated)], or an authorize method. Without one of those, the struct does not compile. Field Notes is not a public paste bin, so storing a note requires an authenticated user.

#[laravel::input(fills = Note)] marks StoreNote as the only data allowed into a new Note. create! then ignores anything the struct does not declare. A client who posts user_id does not get to choose the author.

use laravel::prelude::*;
use laravel::validation::validate;

use crate::models::Note;

#[laravel::input(fills = Note)]
#[validate(authenticated)]
pub struct StoreNote {
    #[validate(required, max_length(120))]
    pub title: String,

    #[validate(required)]
    pub body: String,
}

Valid<StoreNote> reads and validates the body. It has to be the handler’s last argument. Authenticated<User> is the user who passed #[validate(authenticated)]. On a web route, a guest is redirected to the login page. A JSON client gets 401. A failed rule redirects back with the errors, or returns 422 for JSON.

use laravel::auth::Authenticated;
use laravel::model::create;
use laravel::validation::Valid;

use crate::models::{Note, User};

pub async fn store(
    Authenticated(user): Authenticated<User>,
    Valid(form): Valid<StoreNote>,
) -> laravel::Result<Redirect> {
    let note = create!(Note {
        user: &user,
        ..form
    }).await?;

    Ok(redirect!(notes::show, &note))
}

..form fills title and body from the validated struct. user: &user sets the relationship from the session, which is the models guide’s way to assign a belongs-to. The extra user_id in the body has nowhere to land.

Register POST /notes in web.rs, inside the Authenticate group from the HTTP course. The struct’s authenticated check and the middleware agree. Keeping both means a JSON client and a browser fail in the way each expects.

#[validate(anyone)] is the other documented choice. Use it only for a form a guest is supposed to submit, such as the login form in the next lesson. It is not a temporary shortcut for notes.

Rules you will reuse: required, email, max_length, min, confirmed. A field can list several. The validation guide is the list. If a rule you remember from PHP Laravel is not on that page, do not guess its Rust name.

Check your work

POST a title longer than 120 characters and an extra user_id. The title is rejected; the saved author is the logged-in user.

Back to roadmap