Laravel for Rust เขียน route, handler และ validation เทียบกับ PHP

Laravel for Rust ยังเขียน route แบบ routes/web.php แต่ชี้ไปที่ async function แทน controller ส่วน FormRequest กลายเป็น struct ที่มี rule อยู่บน field ตอบ 422 หน้าตาเดียวกับ PHP และ compile ไม่ผ่านถ้าไม่บอกว่าใครส่งได้ หน้า Inertia ก็ render ตาม protocol v3 ให้ frontend ตัวเดิมใช้ต่อได้

ในโพสต์นี้ 8 หัวข้อ
  1. แอปทั้งตัว build ออกมาเป็น binary ไฟล์เดียว
  2. route และ route group ยังเขียนเหมือน routes/web.php
  3. handler เป็น async function ไม่ต้องมี controller class
  4. FormRequest กลายเป็น struct ที่มี rule อยู่บน field
  5. ทุกฟอร์มต้องบอกว่าใครส่งได้ ไม่อย่างนั้น compile ไม่ผ่าน
  6. view เป็น Jinja และเห็นแค่ข้อมูลที่ handler ส่งมา
  7. หน้า Inertia ใช้ frontend React หรือ Vue ตัวเดิมได้
  8. route ฝั่ง web ต้องมี APP_KEY ก่อน

Laravel for Rust คือ Laravel ที่ Taylor Otwell เขียนขึ้นใหม่ด้วย Rust โพสต์นี้ดูชั้น HTTP ของเวอร์ชัน 0.1 ที่ยังเป็น beta โดยวางโค้ด PHP ที่เราคุ้นไว้ก่อน แล้วดูว่าฝั่ง Rust ต่างไปตรงไหน ตัวอย่างมาจากแอปจดโน้ตชื่อ notes

แอปทั้งตัว build ออกมาเป็น binary ไฟล์เดียว

เริ่มโปรเจกต์ใหม่ด้วย Laravel CLI ตัวใหม่ ซึ่งต้องมี Rust 1.99 ขึ้นไปในเครื่องก่อน

laravel new notes --rust

โปรเจกต์ของ Rust เรียกว่า crate มี Cargo.toml ทำหน้าที่แบบ composer.json ชื่อ package ตั้งตามชื่อโปรเจกต์ได้ แต่ส่วน [lib] ต้องชื่อ app เพราะ framework หา command, listener, seeder และ config ที่เราเขียนจาก library ชื่อนี้ ในโค้ดเราจึง use app::models::User ได้ ส่วนไฟล์โปรแกรมที่ build ออกมาจะตั้งชื่อตาม package

[package]
name = "notes"
edition = "2024"
rust-version = "1.99"

# เปลี่ยนชื่อ package ได้ แต่ lib ต้องชื่อ app
[lib]
name = "app"

[dependencies]
laravel-rust = { version = "0.1", features = ["database-postgres"] }
serde = { version = "1", features = ["derive"] }

ฐานข้อมูลเริ่มต้นคือ PostgreSQL ถ้าจะใช้ MySQL หรือ SQLite ให้เปลี่ยน feature database-postgres เป็นตัวที่ต้องการ ไฟล์หลักเทียบกับ Laravel PHP ได้แบบนี้

Laravel for Rust Laravel PHP
src/main.rs public/index.php กับ artisan รวมกัน
src/app.rs bootstrap/app.php
src/routes/web.rs, api.rs routes/web.php, api.php
src/http/handlers/notes.rs controller กับ FormRequest
resources/views/*.html Blade view (เขียนแบบ Jinja)

src/main.rs แค่เรียก app::configure().run() รันเปล่า ๆ จะเปิด server ถ้าใส่ชื่อคำสั่งก็รันคำสั่งนั้น ระหว่างเขียนโค้ดเราสั่งผ่าน Laravel CLI เช่น laravel route:list ซึ่ง build แอปให้แล้วรันคำสั่งต่อทีเดียว (เครื่องที่ไม่มี CLI ใช้ cargo run -- route:list แทนได้) ส่วน laravel dev เปิดแอป, queue worker และ Vite พร้อมกัน พอ build สำหรับ production เสร็จ เราจะได้ไฟล์ notes ที่ใช้แทน php artisan บน server ได้เลย เช่น ./notes migrate --force หรือ ./notes queue:work (queue และ scheduler แยกไว้อีกโพสต์)

src/app.rs เขียนตาม bootstrap/app.php ของ Laravel 11 ขึ้นไปแทบบรรทัดต่อบรรทัด

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->web(append: [HandleInertiaRequests::class]);
    })
    ->create();

ฝั่ง Rust ชื่อ method เปลี่ยนเป็น snake_case ส่ง function ของ route แทน path ของไฟล์ และบอกที่อยู่ของ migration ไว้ตรงนี้ด้วย

use laravel::Application;
use laravel::foundation::ApplicationBuilder;

use crate::handlers::inertia::HandleInertiaRequests;

pub fn configure() -> ApplicationBuilder {
    Application::configure()
        .with_routing(|routing, _| {
            routing.web(crate::routes::web::routes);
            routing.api(crate::routes::api::routes);
        })
        .with_middleware(|middleware, _| {
            middleware.web(|web| {
                web.append(laravel::inertia::middleware(HandleInertiaRequests));
            });
        })
        .with_migrations(laravel::db::migrations!("database/migrations"))
}

ส่วน |routing, _| { ... } คือ closure แบบ function ($routing) { ... } ส่วนชื่อที่ลงท้ายด้วย ! คือ macro เป็นโค้ดที่ compiler ขยายให้ตอน build migrations!(...) จึงฝัง migration ทุกไฟล์ลงใน binary ไปด้วย (model และ migration อยู่อีกโพสต์)

route และ route group ยังเขียนเหมือน routes/web.php

// routes/web.php
Route::get('/', [NoteController::class, 'home']);
Route::get('/notes', [NoteController::class, 'index']);

Route::prefix('admin')->middleware('auth')->group(function () {
    Route::get('/', [AdminController::class, 'dashboard']);
});

// routes/api.php
Route::post('/notes', [NoteController::class, 'store']);
Route::get('/notes/{note}', [NoteController::class, 'show']);

ฝั่ง Rust แต่ละไฟล์เป็น function ที่รับ route เข้ามา แล้วชี้แต่ละ route ไปที่ function ใน src/http/handlers

// src/routes/web.rs
use laravel::auth::Authenticate;
use laravel::routing::Router;

use crate::handlers::{admin, notes};

pub fn routes(route: &mut Router) {
    route.get("/", notes::home);
    route.get("/notes", notes::index);

    route.prefix("/admin").middleware(Authenticate).group(|route| {
        route.get("/", admin::dashboard);
    });
}

// src/routes/api.rs
use laravel::routing::Router;

use crate::handlers::notes;

pub fn routes(route: &mut Router) {
    route.post("/notes", notes::store);
    route.get("/notes/{note}", notes::show);
}

prefix(), middleware() และ group() ต่อกันแบบเดียวกับ PHP และมี resource!(photos) แทน Route::resource route ใน api.rs ได้ prefix /api กับ middleware group api ให้เอง ส่วน Authenticate คือ middleware auth ซึ่งต้องลงทะเบียน session guard ด้วย with_auth ใน src/app.rs ก่อน

จุดที่ต่างจริง ๆ คือ route ไม่มีชื่อ ตัว handler เป็นตัวระบุ route แทน url::route(notes::show, 1) ใช้แทน route('notes.show', 1) และ Redirect::route(notes::index, ()) ใช้แทน to_route('notes.index') ถ้าลบหรือเปลี่ยนชื่อ function ที่ลิงก์ถึง compiler ก็ไม่ยอม build

./notes route:list
Method         URI                Handler
GET|HEAD       /                  notes::home
GET|HEAD       /notes             notes::index
GET|HEAD       /admin             admin::dashboard
POST           /api/notes         notes::store
GET|HEAD       /api/notes/{note}  notes::show
GET|POST|HEAD  /_workflow/resume  laravel::url::accept

/_workflow/resume เป็น route ที่ framework เพิ่มให้สำหรับ durable workflow ถ้าเราลงทะเบียน GET /notes ซ้ำสองครั้ง แอปจะไม่ยอม start และบอกว่า `GET /notes` is registered twice ส่วน PHP ให้ route ตัวหลังทับตัวแรกไปเงียบ ๆ

handler เป็น async function ไม่ต้องมี controller class

Rust ไม่มี controller class เราเขียน function ทีละตัว แล้วรวมเรื่องเดียวกันไว้ในไฟล์เดียว src/http/handlers/notes.rs จึงเท่ากับ NoteController argument ของ handler คือสิ่งที่อยากได้จาก request คล้าย method injection ส่วนค่าที่ return คือ response

public function show(Note $note): Note
{
    return $note;
}

route model binding ยังอยู่ แค่ใส่ type Note เป็น argument framework จะหาค่า {note} ใน route แล้วโหลด model มาให้

pub async fn show(note: Note) -> Json<Note> {
    Json(note)
}

async fn คือ function ที่หยุดรอฐานข้อมูลได้โดยไม่บล็อก request อื่น จุดที่รอจะมี .await ต่อท้าย ส่วน Json(note) แปลง model เป็น JSON ถ้าไม่เจอ id นั้นหรือ id ไม่ใช่ตัวเลข ก็ได้ 404 แบบเดียวกับ PHP

curl -i localhost:8000/api/notes/99
HTTP/1.1 404 Not Found
{"message":"Not Found"}

อยากหาด้วย column อื่นก็เขียน {post:slug} ได้เหมือนเดิม

FormRequest กลายเป็น struct ที่มี rule อยู่บน field

class StoreNoteRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'title' => ['required', 'max:100'],
            'body' => ['required', 'min:3'],
        ];
    }
}

public function store(StoreNoteRequest $request): Note
{
    return Note::create($request->validated());
}

ฝั่ง Rust รวม field, rule, สิทธิ์ และการบันทึกลง model ไว้ใน struct ตัวเดียว

use laravel::http::Json;
use laravel::model::{Fill, create};
use laravel::validation::{Valid, Validate};
use serde::Deserialize;

use crate::models::Note;

#[derive(Deserialize, Validate, Fill)]
#[validate(anyone)]
#[fills(Note)]
pub struct StoreNote {
    #[validate(required, max_length(100))]
    pub title: String,
    #[validate(required, min_length(3))]
    pub body: String,
}

pub async fn store(Valid(input): Valid<StoreNote>) -> laravel::Result<Json<Note>> {
    let note = create!(Note { ..input }).await?;

    Ok(Json(note))
}

struct คือ class ที่มีแต่ property และทุก field มี type #[derive(...)] คือการบอก compiler ให้สร้างโค้ดให้ตอน build Deserialize อ่าน JSON หรือ form ลง struct, Validate สร้างโค้ดตรวจจาก #[validate(...)] และ Fill ใส่ค่าลง model

handler ที่รับ Valid<StoreNote> จะทำงานเมื่อ input ผ่านทุก rule เหมือน type-hint StoreNoteRequest ใน controller laravel::Result<...> เป็นได้ทั้งผลลัพธ์หรือ error และ ? ท้ายบรรทัดแปลว่าถ้า error ให้ส่ง error นั้นออกไปเลย คล้ายการโยน exception ให้ framework แปลงเป็น response

ชื่อ rule ส่วนใหญ่ตรงกับ PHP ยกเว้น rule ที่ PHP ใช้ชื่อเดียวกับหลาย type เช่น max แยกเป็น max_length (ข้อความ), max_items (array), max_value (ตัวเลข) และ max_kilobytes (ไฟล์) ส่วน in เปลี่ยนเป็น one_of ถ้าเผลอพิมพ์ max(100) ก็ compile ไม่ผ่าน input จะแปลงลง type ของ field ก่อนแล้วค่อยตรวจ rule field ที่เป็น String จึงรับแค่ข้อความ ถ้ายอมให้ส่ง null ต้องเป็น Option<String> เวลาส่งข้อมูลไม่ผ่านจะได้ 422 แบบนี้

curl -i -X POST localhost:8000/api/notes \
  -H 'Accept: application/json' -H 'Content-Type: application/json' \
  -d '{"title":"","body":"hi"}'
HTTP/1.1 422 Unprocessable Entity
{"message":"The title field is required. (and 1 more error)","errors":{"title":["The title field is required."],"body":["The body field must be at least 3 characters."]}}

JSON หน้าตาเดียวกับ PHP ทุกตัวอักษร frontend ที่อ่าน errors อยู่แล้วจึงไม่ต้องแก้ ฟอร์มจาก browser บน route ฝั่ง web จะได้ redirect กลับพร้อม error กับ old input หน้า Inertia ได้ error ใน prop errors และฟอร์มที่ไม่มี CSRF token ได้ 419 เหมือนกัน

ทุกฟอร์มต้องบอกว่าใครส่งได้ ไม่อย่างนั้น compile ไม่ผ่าน

ใน PHP ถ้า FormRequest ไม่มี authorize() Laravel จะถือว่าใครก็ส่งได้ ฝั่ง Rust ไม่มีค่าเริ่มต้นแบบนั้น struct ที่ใช้กับ Valid ต้องเลือกหนึ่งในนี้

  • #[validate(anyone)] ใครก็ส่งได้
  • #[validate(authenticated)] ต้องล็อกอิน แบบ middleware auth
  • #[validate(authorize(NotePolicy::update, route("note")))] เรียก policy กับ model ที่ route ชี้ถึง ไม่ผ่านได้ 403
  • เขียน authorize() เอง ผ่าน trait ValidatesRequest (trait คือ interface ของ Rust)

ถ้าลบ #[validate(anyone)] ออก compiler จะไม่ยอม build และบอกทางเลือกทั้งหมดมาในข้อความเดียว

cargo build
error[E0277]: `StoreNote` doesn't say who may submit it
    --> src/http/handlers/notes.rs:19:34
     |
  19 | pub async fn store(Valid(input): Valid<StoreNote>) -> laravel::Result<Json<Note>> {
     |                                  ^^^^^^^^^^^^^^^^ `StoreNote` doesn't implement `ValidatesRequest`
     |
     = note: implement `ValidatesRequest` for `StoreNote` with `async fn authorize(request: &Request) -> laravel::Result<bool>`, or add `#[validate(authorize(PostPolicy::update))]` to check a policy, or `#[validate(authenticated)]` to let any logged-in user submit it, or `#[validate(anyone)]` to let anyone submit it

ส่วน $fillable หายไปทั้งก้อน #[fills(Note)] กับ create!(Note { ..input }) ทำงานแบบ Note::create($request->validated()) โดย compiler เช็คว่าทุก field มี column ชื่อเดียวกันใน model และ type เข้ากันได้ ถ้าเพิ่ม field tags ที่ model ไม่มีก็ build ไม่ผ่าน ค่าที่ request ส่งเกินมาไปไม่ถึง model อยู่แล้ว ส่วน field ที่ไม่อยากบันทึกใส่ #[fill(skip)]

view เป็น Jinja และเห็นแค่ข้อมูลที่ handler ส่งมา

view() กับ data! ทำงานแบบ view('notes.index', compact('notes')) ชื่อ view ยังใช้จุดแทนโฟลเดอร์เหมือนเดิม

use laravel::view::{View, data, view};

pub async fn home() -> laravel::Result<View> {
    let notes = Note::query().latest(Note::created_at).get().await?;

    Ok(view("notes.index", data! { notes }))
}

ไฟล์ resources/views/notes/index.html เขียนด้วย syntax ของ Jinja ผ่าน minijinja

<h1>Notes ({{ notes | length }})</h1>
<ul>
  {% for note in notes %}
    <li><strong>{{ note.title }}</strong>: {{ note.body }}</li>
  {% else %}
    <li>No notes yet.</li>
  {% endfor %}
</ul>

{{ }} escape HTML ให้เหมือน Blade, {% for %}…{% else %} ทำงานแบบ @forelse และมี helper อย่าง csrf_field(), old('title'), error('title') กับ vite(...) แก้ไฟล์ .html แล้ว refresh ก็เห็นผลเลยโดยไม่ต้อง build ใหม่

ที่ต้องปรับตัวคือ template เรียก function ของ PHP ไม่ได้ เห็นแค่ข้อมูลที่ส่งมา ข้อมูลที่ share ให้ทุก view และ helper ข้างบน ถ้า print หรือวน loop ตัวแปรที่ไม่ได้ส่งมา หน้าจะ error 500 ว่า undefined value พร้อมชื่อไฟล์และบรรทัด เช่นเขียน {{ config.app.name }} แบบ config('app.name') ใน Blade ให้ใช้ global app_name แทน ส่วน {% if title %} ยังเช็คตัวแปรที่อาจไม่มีได้

หน้า Inertia ใช้ frontend React หรือ Vue ตัวเดิมได้

return Inertia::render('Notes/Index', [
    'notes' => Note::latest()->get(),
]);

ฝั่ง Rust handler return Page จาก inertia::render ส่วน HandleInertiaRequests เป็น struct ที่ implement trait inertia::Middleware แล้วต่อท้าย group web ใน src/app.rs

// src/http/handlers/notes.rs
use laravel::inertia::{self, Page, props};

pub async fn index() -> laravel::Result<Page> {
    let notes = Note::query().latest(Note::created_at).get().await?;

    Ok(inertia::render("Notes/Index", props! { notes => notes }))
}

// src/http/handlers/inertia.rs
use laravel::http::Request;
use laravel::inertia::{self, Props, props};

pub struct HandleInertiaRequests;

impl inertia::Middleware for HandleInertiaRequests {
    async fn share(&self, _request: &Request) -> laravel::Result<Props> {
        Ok(props! { app_name => laravel::config().app.name.clone() })
    }
}

props! { ... } ทำหน้าที่แบบ array ['notes' => $notes] และ share() ก็คือ share() ของ PHP root view ย้ายจาก app.blade.php ไปที่ resources/views/app.html โดย vite(...), inertia_head กับ inertia แทน @vite, @inertiaHead กับ @inertia

<head>
  {{ vite("resources/js/app.tsx", "resources/js/pages/" ~ page.component ~ ".tsx") }}
  {{ inertia_head }}
</head>
<body>
  {{ inertia }}
</body>

ลองส่ง request แบบที่ Inertia ส่งตอนคลิกเปลี่ยนหน้า

curl localhost:8000/notes -H 'X-Inertia: true'
{"component":"Notes/Index","props":{"errors":{},"app_name":"Notes","head":["<title data-inertia=\"title\">Notes</title>"],"notes":[{"id":1,"title":"First note","body":"Laravel for Rust feels familiar","words":0,"created_at":"2026-12-01T06:32:20.691156Z","updated_at":"2026-12-01T06:32:20.691156Z"}]},"url":"/notes","version":"","sharedProps":["errors","app_name","head"]}

page object มี component, props, url, version และ sharedProps ตาม protocol ของ Inertia v3 การเปิดหน้าครั้งแรกก็ได้ <script data-page="app" type="application/json"> กับ <div id="app"> แบบเดียวกับ Laravel PHP createInertiaApp ฝั่ง React หรือ Vue จึงไม่ต้องรู้ว่า server เป็น Rust ส่วน SSR เปิดได้ด้วย INERTIA_SSR=true (หลักการทำงานเหมือนเดิม) ที่ต้องหาทางใหม่คือเครื่องมือที่เรียก php artisan อยู่เบื้องหลัง เช่น Wayfinder

route ฝั่ง web ต้องมี APP_KEY ก่อน

route ใน group web ผ่าน middleware ชุดเดียวกับ PHP ดูได้จาก route:list -v

./notes route:list -v --path admin
Method    URI     Handler
GET|HEAD  /admin  admin::dashboard
                  ⇂ EncryptCookies
                  ⇂ StartSession
                  ⇂ PreventRequestForgery
                  ⇂ HandleInertiaRequests
                  ⇂ Authenticate

EncryptCookies กับ StartSession เข้ารหัส cookie ของ session และ XSRF-TOKEN ด้วย APP_KEY ในรูปแบบเดียวกับ Laravel PHP (JSON ที่มี iv, value, mac, tag แล้ว encode เป็น base64) ส่วน PreventRequestForgery คือตัวเช็ค CSRF

ถ้ายังไม่ได้ตั้ง APP_KEY route ฝั่ง api ยังตอบได้ตามปกติ แต่ทุก route ฝั่ง web จะได้ 500 ว่า no application encryption key has been specified แก้ด้วย ./notes key:generate ซึ่งเขียน key รูปแบบ base64:... ลง .env แบบเดียวกับ php artisan key:generate

ส่วน model Note ที่ handler ทุกตัวใช้ ลองอ่านต่อได้ที่ model และ migration ใน Laravel for Rust ครับ

ตอนถัดไปของซีรีส์ Laravel for Rust

อ่านต่อ

ถูกอ้างถึงใน

ล่าสุด

ดูทั้งหมด →