Laravel, Laravel Go and Laravel Rust, side by side
Laravel now has official Go and Rust editions, Laravel Go and Laravel Rust, that keep its routes, middleware, queues and conventions. You may also see them called “Laravel for Go” and “Laravel for Rust”. Here is one blog app (users, posts and comments) written in all three, from installing to deploying, with notes on what carries over and what changes.
Code is written for the versions below and works on anything newer unless a snippet carries a version tag such as Go 1.27+. Latest releases checked December 5, 2026.
Laravel
Written for
13.x
Latest release
13.45.0
Works on
Laravel 13 on PHP 8.3+
Laravel 13 conventions: attribute-based models such as #[Fillable], and PreventRequestForgery for CSRF. Most snippets also work on Laravel 12. Release notes
Laravel Go
Written for
0.2.0
Latest release
0.2.0
Works on
v0.2 on Go 1.27+
Beta: the API may change before 1.0. Every snippet comes from the v0.2.0 docs. Release notes
Laravel Rust
Written for
0.2.0
Latest release
0.2.0
Works on
v0.2 on Rust 1.99+ (2024 edition)
Beta: the API may change before 1.0. Every snippet comes from the v0.2.0 docs. Release notes
Framework basics
Getting a project running and handling one request, from install to Artisan commands. Laravel Go and Laravel Rust keep the names you know (routes, middleware, .env, laravel migrate), but your app is a compiled, long-running binary: Go passes the request around as a context.Context, and Rust builds each handler argument with a typed extractor.
All three start with laravel new. The Go and Rust ports use the new Laravel CLI, which asks for a language, and laravel dev rebuilds and restarts a compiled server on save instead of PHP re-reading your files on every request.
Laravel
# needs PHP, Composer and Nodecomposer global require laravel/installer
laravel new blog # starter kit, database, tests...cd blog
php artisan migrate
composer run dev # server + queue + logs + Vite# or just the web server:php artisan serve # http://127.0.0.1:8000# production: Nginx + PHP-FPM serve public/index.php# (no compile step, deploy the source)
Laravel Go
# needs Go 1.27+, Node and Gitcurl -fsSL https://laravel.com/install.sh | sh
laravel new blog --go# module is always named "app"cd blog
laravel migrate # PostgreSQL by default (DATABASE_URL)laravel dev # server + queue worker + Vite# http://127.0.0.1:8000, rebuilds on every .go / .env save# production: one binary (+ public/ and storage/ beside it)npm run build
go build -o app .
./app # no args = serve
Laravel Rust
# needs Rust 1.99+ (rustup), Node and Gitcurl -fsSL https://laravel.com/install.sh | sh
laravel new blog --rust # library crate is always named "app"cd blog
laravel migrate # PostgreSQL by default (DATABASE_URL)laravel dev # server + queue worker + Vite# http://127.0.0.1:8000, rebuilds on every src/ / .env save# production: an optimised release buildnpm run build
cargo run --release
Tip. Same as Laravel: .env is created and APP_KEY generated for you, laravel migrate creates the users, sessions and queue tables. New apps ship with Inertia + React + TypeScript + Tailwind, like Laravel's React starter kit (there is no starter-kit choice).
Laravel Go. Different: the new CLI is a standalone binary (~/.laravel/bin/laravel). If Herd or the Composer installer is earlier on your PATH, laravel --version will not start with Laravel CLI; fix the PATH order.
Laravel Rust. The first laravel dev compiles the whole dependency tree (framework, Tokio, Axum, database driver), so expect minutes, not seconds. New apps share one Cargo build cache across projects to save disk.
Watch out. Both ports are beta (v0.2). Releases before 1.0 may break APIs and configuration, so pin the version (go.mod / Cargo.toml) and read the upgrade guide before bumping.
The folders look familiar: routes/, database/migrations/, resources/views/, storage/, public/. The big change is that the Go and Rust apps have no app/ namespace and almost no config/ files, and nothing is auto-discovered by scanning folders the way Laravel scans app/.
Laravel Go. Each folder is a Go package imported by path (app/models, app/handlers/posts). Jobs, listeners and commands must be listed (jobs.All, listeners.All, commands.All); a listener you forget to list is never called and nothing warns you.
Laravel Go. There is no middleware/ package on purpose: it would clash with Laravel's own middleware package. Put each middleware in the feature package it belongs to (billing.Subscribed).
Laravel Rust. Commands, listeners, jobs, services and config sections are discovered by their attributes, but only in modules Rust compiles. Forget the mod line in src/lib.rs or a mod.rs and the file is silently skipped.
Laravel. Mapping: app/Http/Controllers -> handlers/ or src/http/handlers, app/Providers -> services/ or src/app.rs hooks, config/*.php -> mostly .env plus Configure (Go) or src/config/*.rs (Rust).
All three read .env and let real environment variables win. Laravel copies values into config/*.php arrays you read with config('a.b'); the ports give you typed config instead, so a misspelled key fails to compile and a bad value (like APP_DEBUG=maybe) stops the app at startup.
Laravel Go.config.From(ctx) reads the framework config from any context (a request, a job, a command). New apps have no config files: settings an env var cannot express go in a Configure(cfg *config.Config, env *config.Env) function in bootstrap/app.go.
Laravel Go.env.Require("STRIPE_KEY") refuses to start without the variable, but the docs advise an empty fallback for secrets instead, because services.New runs for every command, including key:generate on a fresh clone.
Laravel Rust. A #[derive(Section)] struct is your config/blog.php: each field names its variable with #[env(..)] (required, default = .., seconds, separator = ","). It needs no registration; read it as a Section<T> handler argument or laravel::config().section::<T>().
Watch out. Unlike PHP-FPM, the config is built once and shared by every request, so treat it as read-only. There is no config:cache, and no config(['key' => 'value']) at runtime.
Under PHP-FPM, Laravel boots the whole framework for every request and then forgets everything. The Go and Rust apps boot once: main builds the application, then the same process serves every request concurrently, so anything you keep in memory is shared by all of them.
Laravel
// public/index.php: runs on EVERY request under PHP-FPMrequire __DIR__.'/../vendor/autoload.php';
$app = require_once __DIR__.'/../bootstrap/app.php'; // boot$app->handleRequest(Request::capture());
// kernel -> global middleware -> router -> web/api group// -> controller -> response; then the process resets// bootstrap/app.phpreturnApplication::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
health: '/up',
)
->withMiddleware(function (Middleware$middleware): void {
//
})
->create();
Laravel Go
// main.go: runs ONCE, then serves every requestfuncmain() {
laravel.Run(bootstrap.Options()) // no args: serve; "migrate": run it
}
// bootstrap/app.gofuncOptions() laravel.Options {
return laravel.Options{
Routes: laravel.Routes{
Web: routes.Web,
API: routes.API,
Health: "/up",
},
Services: laravel.BuildServices(services.New), // built once
}
}
// per request (one goroutine each): kernel -> global middleware// -> router -> web/api group -> route middleware -> handlerfuncShow(r *web.Request) *web.Response {
r.OnFinish(func() { /* runs after the response is sent */ })
return web.Text("Hello")
}
Laravel Rust
// src/main.rs: runs ONCE, then Tokio serves every requestuse std::process::ExitCode;
fnmain() -> ExitCode {
app::configure().run() // no args: serve; "migrate": run it
}
// src/app.rsuse laravel::Application;
use laravel::foundation::ApplicationBuilder;
usecrate::routes;
pubfnconfigure() -> ApplicationBuilder {
Application::configure()
.with_routing(|routing, _| {
routing
.web(routes::web::routes)
.api(routes::api::routes)
.health("/up");
})
}
// per request (async task): kernel -> global middleware// -> router -> web/api group -> route middleware -> handler
Tip. Same as Laravel: the stages (kernel, global middleware, router, web/api group, route middleware, handler, response back out in reverse) and the /up health route are deliberately identical.
Laravel Go. Startup checks run before the first request: an invalid env variable or two routes answering the same request make laravel.Run print every problem and exit. On SIGTERM the server drains requests for up to SERVER_SHUTDOWN_TIMEOUT (20 s).
Laravel Rust. Registration and boot run once: package providers first, then your with_* callbacks, then the booted callbacks in src/app.rs. Services are not built at boot: each #[singleton] is created on first use and then shared.
Watch out. A long-running process changes the rules PHP let you ignore: static or global state leaks between requests, and shared services must be safe to use from many goroutines or tasks at once. Pass per-request values (the user) as arguments, never as fields on a service.
The router API is almost a transliteration: verbs, {params}, prefixes, groups and middleware. The differences are in names and constraints: Go keeps named routes and Where, while Rust has no route names (you link to the handler function itself) and uses the parameter's type as its constraint.
// src/routes/web.rsuse laravel::auth::{Authenticate, RequireVerifiedEmail};
use laravel::prelude::*;
usecrate::http::handlers::{admin, posts};
pubfnroutes(route: &mutRouter) {
route.get("/posts", posts::index);
route.get("/posts/{post}", posts::show); // show(post: Post) or Params<u64>
route.post("/posts", posts::store).middleware(Authenticate);
route
.prefix("/admin")
.middleware((Authenticate, RequireVerifiedEmail))
.group(|route| {
route.get("/posts", admin::posts::index);
route.delete("/posts/{post}", admin::posts::destroy);
});
}
// no route names: link to the handler itself// let url = route!(posts::show, 42)?;
Laravel Go. Route files are plain functions that receive the router and the typed config, so if cfg.App.Env == config.Local { ... } can register local-only routes. Middleware are values (auth.Authenticate{}), not string aliases like 'auth'.
Laravel Rust.route!(posts::show, &post)? and redirect!(...) take the handler path, so renaming a handler breaks the build instead of a link. A param that does not parse into its type (Params<u64> with /posts/abc) is a 404, which replaces whereNumber.
Tip. All three have laravel route:list (php artisan route:list in PHP), resource routes (route.Resource("photos", routing.Resource{...}) in Go, resource!(photos) in Rust), redirect routes and view routes.
Laravel. Wildcards differ: Laravel uses {path} with ->where('path', '.*'), Go writes {path...} and Rust writes {*path}. Optional {year?} works in all three.
There are no controller classes in the ports. A Go handler is a plain function func(r *web.Request) *web.Response; a Rust handler is an async fn whose arguments are extractors that Laravel builds before calling it, so route-model binding and FormRequest-style validation happen in the signature.
typeNewPoststruct { // handlers/posts/posts.goTitlestring`json:"title"`Bodystring`json:"body"`
}
func (f *NewPost) Rules() validation.Rules {
return validation.For(f, rule.Field(&f.Title, rule.Required, rule.Max(255)), rule.Field(&f.Body, rule.Required))
}
funcShow(r *web.Request) *web.Response {
post, err := model.FromRoute[models.Post](r, "post")
if err != nil {
return web.Fail(err) // 404 when the post does not exist
}
return web.View("posts.show", post)
}
funcStore(r *web.Request) *web.Response {
form, err := r.Validate[NewPost]()
if err != nil {
return web.Fail(err) // back with errors, or 422 JSON
}
post := models.Post{Title: form.Title, Body: form.Body}
if err := model.Create(r, &post); err != nil {
return web.Fail(err)
}
return web.RedirectRoute("posts.show", "post", &post)
}
Laravel Rust
// src/http/handlers/posts.rsuse laravel::model::create;
use laravel::prelude::*;
use laravel::view::View;
usecrate::models::Post;
#[laravel::input(fills = Post)]#[validate(authenticated)]// who may submit, like FormRequest::authorizepubstructNewPost {
#[validate(required, max_length(255))]pub title: String,
#[validate(required)]pub body: String,
}
pubasyncfnshow(post: Post) -> View { // 404 before show() runsview("posts.show", data! { post })
}
pubasyncfnstore(Valid(input): Valid<NewPost>) -> laravel::Result<Redirect> {
let post = create!(Post { ..input }).await?;
Ok(redirect!(show, &post))
}
Laravel Go. Errors are values: every fallible call returns err, and return web.Fail(err) lets Laravel render it (404 for a missing model, redirect-back or 422 for invalid input, 500 otherwise). The *web.Request is also a context.Context, so pass r to every query.
Laravel Go. Group handlers by resource in one package (handlers/posts), so routes read posts.Index, posts.Store. Shared dependencies come from services.From(r), not constructor injection.
Laravel Rust.Valid<T> and Request read the body, so only one of them is allowed and it must be the last argument (a wrong order fails with this function can't handle requests; add #[debug_handler] to see why). Every #[laravel::input] struct must say who may submit it (anyone, authenticated or an authorize function), or the handler does not compile.
Tip. New in Go 1.27: a method may declare its own type parameters, which is what makes r.Validate[NewPost]() and r.Bind[T]() possible. It is one reason Laravel Go needs Go 1.27; on older Go you would write a generic function instead.
Laravel merges query, body and route values behind $request->input(). The ports keep them apart on purpose: route params, query string and body each have their own typed reader, so a query parameter can never sneak into your form data.
Laravel Go.web.Request embeds Go's *http.Request, so r.Header, r.URL, r.Method and r.PathValue are the standard library ones. For typed filters, r.Query[T]() / r.QueryInto(&f) parse the query string into a struct and quietly drop bad optional values.
Laravel Rust. Headers come back as Option<&str> and must be unwrapped. Prefer Laravel's Query<T> and Valid<T> over Axum's own Query/Form extractors: the Axum ones answer bad input with plain text and skip your error handling.
Tip. Same as Laravel: TrimStrings and ConvertEmptyStringsToNull run by default, uploads are checked by their bytes (not the client file name), and a failed parse or validation redirects browsers back and returns 422 JSON to API clients.
Laravel. There is no $request->all() or $request->input('x') for ad-hoc reads. You describe the fields as a struct; for the raw body use io.ReadAll(r.Body) (Go) or request.content() (Rust), for example to verify a webhook signature.
Every Go handler returns one type, *web.Response, built with web.JSON, web.View, web.Redirect... and changed with WithStatus/WithHeader. Rust handlers return anything that implements IntoResponse, so the return type documents what the route sends.
Laravel Go. Structs become JSON through their json tags, and a field tagged json:"-" is hidden (the generated User hides its password this way), which replaces Eloquent's $hidden. Need two values for one header? Use res.Header.Add, the standard http.Header.
Laravel Rust. When branches return different kinds of response, Rust needs one return type: return Response and call .into_response() on each branch. Json, Created, NoContent, Redirect, View, File and plain strings all work as return types.
Tip. Same helpers you know: web.Created / Created(post) for 201, web.Back() / Redirect::back(), WithCookie / with_cookie, streamed responses, and downloads of generated content (web.Attachment, Download::new).
Blade compiles to PHP; the ports use their language's template engines. Go views are Go's html/template ({{.Title}}, {{range}}, {{template}} + {{define}}), while Rust views use Jinja syntax ({% extends %}, {% block %}, {% for %}), which reads much more like Blade.
Tip. Same as Laravel: views live in resources/views, dot names map to folders (admin.profile), every value is escaped by default, and route, vite, CSRF and old-input helpers exist. New apps still default to Inertia + React; views serve server-rendered pages, the Inertia root view and emails.
Laravel Go.html/template has no operators: write eq .Status "paid", and, len .Orders, and pipes like {{.Name | upper}}. A view gets one value called .; pass a struct so the compiler checks the fields. Views are embedded in the binary (resources/resources.go), so you deploy one file.
Laravel Rust. Pass data with data! { posts, title => "Posts" } or any Serialize struct. route("posts::show", post) names the handler, and template strings are not checked by the compiler, so cover views with HTTP tests.
Laravel. No Blade components or @props slots in either port. Go components are template calls with dict, Rust uses Jinja include and macros. Read the templates guide before porting a large Blade UI.
The onion is identical: code before next runs before the handler, code after it can change the response. In Go a middleware is any type with a Handle(r, next) method; in Rust it is an async fn marked #[middleware]. Both are registered as values, with no string aliases.
Laravel
// app/Http/Middleware/RequireApiToken.phpclassRequireApiToken
{
publicfunctionhandle(Request$request, Closure$next): Response
{
if ($request->header('X-Api-Token') !== 'my-secret-token') {
abort(403);
}
$start = microtime(true);
$response = $next($request);
$response->headers->set('Server-Timing', 'app;dur='.round((microtime(true) - $start) * 1000));
return$response;
}
}
// bootstrap/app.php: the whole api group
->withMiddleware(function (Middleware$middleware): void {
$middleware->api(append: [RequireApiToken::class]);
})
// routes/web.php: one routeRoute::post('/posts', [PostController::class, 'store'])->middleware(RequireApiToken::class);
Laravel Go
// apitokens/apitokens.gotypeRequiredstruct{}
func (Required) Handle(r *web.Request, next web.Next) *web.Response {
if r.Header.Get("X-Api-Token") != "my-secret-token" {
return web.Abort(http.StatusForbidden) // stop: handler never runs
}
start := time.Now()
res := next(r)
res.Header.Set("Server-Timing", fmt.Sprintf("app;dur=%d", time.Since(start).Milliseconds()))
return res
}
// bootstrap/app.go: the whole api groupMiddleware: func(m *laravel.Middleware, cfg *config.Config) {
m.API.Append(apitokens.Required{})
},
// routes/web.go: one route
route.Post("/posts", posts.Store).Middleware(apitokens.Required{})
Laravel Rust
// src/http/middleware/api_token.rsuse std::time::Instant;
use laravel::http::{Next, Request, Response, middleware};
#[middleware]pubasyncfnrequire_api_token(request: Request, next: Next) -> laravel::Result<Response> {
if request.header("x-api-token") != Some("my-secret-token") {
laravel::abort!(403); // stop: handler never runs
}
let started = Instant::now();
let response = next.run(request).await;
Ok(response.with_header("server-timing", format!("app;dur={}", started.elapsed().as_millis())))
}
// src/app.rs: the whole api group
.with_middleware(|middleware, _| {
middleware.api(|api| {
api.append(require_api_token);
});
})
// src/routes/web.rs: one route
route.post("/posts", posts::store).middleware(require_api_token);
Laravel Go. Short middleware can be plain functions wrapped with web.MiddlewareFunc(fn). Settings go in struct fields (billing.Plan{Name: "team"}), which replaces Laravel's 'role:admin' parameter strings. next always returns a response, even when the handler failed.
Laravel Rust. A middleware may take extractors before request (Auth<User>, Section<T>, Inject<T>) and its own parameters after next, called like ensure_role(Role::Admin) on the route. Parameter types must implement Clone.
Tip. Same ordering as Laravel: global, then the web/api group, then group middleware, then route middleware. Exclude one with .Without(x{}) in Go or .without_middleware::<T>() in Rust, the equivalent of withoutMiddleware().
Watch out. Global middleware run before the session starts, so they cannot see the session or the logged-in user. Put anything that needs auth on the route or in the web group.
There is no artisan file: the compiled app is the console. laravel route:list builds the binary and runs it with arguments, and in production you run ./app migrate --force. Go commands are types with Name/Run and std flag options; Rust commands are #[command] functions whose parameters are parsed by clap.
// No make:command in v0.2: create src/console/publish_posts.rs// and add mod publish_posts; to src/console/mod.rsuse laravel::console::{Console, command};
use laravel::model::update;
usecrate::models::Post;
/// Publish draft posts.#[command("posts:publish")]pubasyncfnpublish_posts(
/// The IDs of the posts to publish.#[arg(required = true)]
ids: Vec<i64>,
/// Publish already published posts again.#[arg(long)]
force: bool,
console: &mutConsole,
) -> laravel::Result<()> {
for id in ids {
letmut post = Post::find_or_fail(id).await?;
if post.published_at.is_none() || force {
update!(post { published_at: laravel::now() }).await?;
console.success(format!("Post `{id}` published."));
}
}
Ok(())
}
// laravel posts:publish 3 7 12 --force
Laravel Go. The ctx passed to Run carries the app like r does in a handler, so db, config.From(ctx) and services.From(ctx) all work. Generators in v0.2: make:command, make:job and make:migration. Commands you write by hand must be added to commands.All.
Laravel Rust. Doc comments become the list and --help text, and the Rust type decides parsing (Option<T> optional, Vec<T> repeated, bool + #[arg(long)] a switch). Commands are discovered by attribute, so there is no list to update, only the mod line.
Watch out. Laravel Rust v0.2 documents only one generator, make:migration. There is no make:command, make:model or make:controller; create the file by hand and declare its module.
Tip. Same as Artisan: laravel list, laravel help <cmd>, -q/-v verbosity, prompts, progress bars and a scheduler. Without the CLI, run go run . route:list or cargo run -- route:list.
Validation, the database, models, auth and the rest of a typical CRUD app. Laravel Go and Laravel Rust keep Laravel's vocabulary (form requests, Eloquent-style models, policies, factories, disks) but replace magic with types: input is a struct, relationships are typed fields that never lazy-load, and migrations only run forward.
A Laravel form request is a class with authorize() and rules(). Both ports turn it into a typed input struct: Go attaches rules with a Rules method that points at each field, Rust puts rules in #[validate(...)] attributes. Failure behaves exactly like Laravel: redirect back with errors on web routes, a 422 JSON body on API routes.
typeStorePoststruct {
Titlestring`json:"title"`Bodystring`json:"body"`
}
func (StorePost) Authorize(r *web.Request) error {
return auth.Authenticated(r) // = authorize(): logged-in users only
}
// Field pointers, not strings: a typo in a field name won't compilefunc (f *StorePost) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Title, rule.Required, rule.Max(255), model.Unique[models.Post]()),
rule.Field(&f.Body, rule.Required),
)
}
funcStore(r *web.Request) *web.Response {
form, err := r.Validate[StorePost]()
if err != nil {
return web.Fail(err) // redirect back (web) or 422 JSON (api)
}
post := models.Post{UserID: r.User[models.User]().ID, Title: form.Title, Body: &form.Body}
if err := model.Create(r, &post); err != nil {
return web.Fail(err)
}
return web.Created(post)
}
Laravel Rust
use laravel::http::Created;
use laravel::model::create;
use laravel::prelude::*;
usecrate::models::{Post, User};
// fills = Post: this struct is also the "fillable" list for Post#[laravel::input(fills = Post)]#[validate(authenticated)]// = authorize(); omit it and the handler won't compilepubstructStorePost {
#[validate(required, max_length(255), unique(Post::title))]pub title: String,
#[validate(required)]pub body: String,
}
// Valid<T> must be the last argument: it reads the bodypubasyncfnstore(
Authenticated(user): Authenticated<User>,
Valid(input): Valid<StorePost>,
) -> laravel::Result<Created<Post>> {
let post = create!(Post { user: &user, ..input }).await?;
Ok(Created(post)) // 201 + JSON, like web.Created
}
Tip. The 422 body is the same shape in all three: {"message": "The title field is required. (and 1 more error)", "errors": {"title": [...]}}, so existing frontends keep working.
Laravel Go. The Go field type is a rule too: an int field rejects abc with "must be an integer" before your rules run. Use *string for nullable fields and validation.Sometimes[T] for PATCH fields that may be left out.
Laravel Rust.Option<T> is a nullable field and Sometimes<T> is "may be left out". Custom messages are inline: required.message("Please enter your :attribute.") plus label = "email address".
Laravel. There is no $request->validate([...]) array form in the ports: validated input is always a struct, which replaces both inline validation and form request classes. For a one-off form, Go accepts an inline var form struct{...} with r.ValidateInto(&form, rule.Field(...)).
DB::select and DB::transaction map almost one to one. Go passes a context.Context (the request r in handlers) to every query, and a transaction is just a context that queries join. Rust binds variables written in {braces} inside db::query! and gives the transaction closure a handle tx.
Laravel
<?php
useIlluminate\Support\Facades\DB;
// ? placeholders are bound, never interpolated$users = DB::select('select id, name from users where active = ?', [true]);
// a second connection defined in config/database.php$total = DB::connection('reporting')->scalar('select count(*) from posts');
// commits on return, rolls back on any exception
DB::transaction(function () use ($postId) {
DB::update('update posts set published_at = now() where id = ?', [$postId]);
DB::insert(
'insert into activity (post_id, action) values (?, ?)',
[$postId, 'published'],
);
});
Laravel Go
type userRow struct {
ID int64Namestring
}
funcActiveUsers(ctx context.Context) ([]userRow, error) {
return db.Select[userRow](ctx, "select id, name from users where active = ?", true)
}
funcPostCount(ctx context.Context) (int64, error) {
// named connection = a copy of ctx whose queries run elsewhere
reporting := db.Connection(ctx, "reporting")
return db.SelectOne[int64](reporting, "select count(*) from posts")
}
funcPublish(ctx context.Context, postID int64) error {
// commits on nil, rolls back on an error or a panicreturn db.Transaction(ctx, func(ctx context.Context) error {
if _, err := db.Exec(ctx, "update posts set published_at = now() where id = ?", postID); err != nil {
return err
}
_, err := db.Exec(ctx, "insert into activity (post_id, action) values (?, ?)", postID, "published")
return err
})
}
Laravel Rust
use laravel::db;
#[derive(Debug, db::FromRow)]structUserRow {
id: i64,
name: String,
}
let active = true;
let users = db::query!("SELECT id, name FROM users WHERE active = {active}")
.select_as::<UserRow>()
.await?;
let reporting = db::connection("reporting")?;
let total = db::query!(reporting, "SELECT COUNT(*) FROM posts")
.scalar::<i64>() // Option<i64>: None when there is no row
.await?
.unwrap_or(0);
// commits on Ok, rolls back on Errlet post_id = 42_i64;
db::transaction(async |tx| {
db::query!(tx, "UPDATE posts SET published_at = NOW() WHERE id = {post_id}")
.update()
.await?;
db::query!(tx, "INSERT INTO activity (post_id, action) VALUES ({post_id}, 'published')")
.insert()
.await?;
Ok(())
})
.await?;
Laravel Go. Configure with DATABASE_URL (the scheme picks the driver). Extra connections go in cfg.Database.Connections in your configure function. A missing row from db.SelectOne is a *db.NotFoundError, which web.Fail turns into a 404.
Laravel Rust. Drivers are Cargo features on laravel-rust (database-postgres, database-mysql, database-sqlite); extra connections are added in src/config/database.rs. It's built on SQLx.
Watch out. Rust's db::query! is notsqlx::query!: it does not check SQL against your schema at compile time, so a misspelled column fails at run time, like PHP.
Tip. Lists need a helper in Go: where role in (?) with db.In(roles). A bare slice binds as one value and most drivers reject it.
DB::table() becomes db.Table() in Go and db::table() in Rust, with the same clause names. The differences are in how you say the row type (Go: Get[T], Rust: a FromRow struct) and how you write conditions (Rust builds them from col(...) expressions joined with & and |).
type authorCount struct {
NamestringPostsint64
}
authors, err := db.Table("posts as p").
Join("users as u", "u.id", "=", "p.user_id").
Select("u.name").
SelectRaw("count(*) as posts").
WhereNotNull("p.published_at").
GroupBy("u.name").
Having("count(*)", ">", 5).
OrderBy("u.name").
Limit(10).
Get[authorCount](ctx) // nothing runs until a method takes ctx
id, err := db.Table("posts").InsertGetID(ctx, db.Values{
"user_id": 1,
"title": "Hello",
})
_, err = db.Table("posts").WhereLt("votes", 0).Delete(ctx)
Laravel Rust
use laravel::db::{self, col, values};
#[derive(db::FromRow, Serialize)]structAuthorCount {
name: String,
posts: i64,
}
let authors: Vec<AuthorCount> = db::table("posts as p")
.join("users as u", col("u.id").eq(col("p.user_id")))
.select(("u.name", col("*").count().alias("posts")))
.filter(col("p.published_at").is_not_null())
.group_by(["u.name"])
.having(col("*").count().gt(5))
.order_by("u.name")
.limit(10)
.get()
.await?;
let id = db::table("posts")
.insert_get_id(values! { user_id: 1, title: "Hello" }, "id")
.await?;
db::table("posts").filter(col("votes").lt(0)).delete().await?;
Laravel Go. Each clause returns a new query, so you may keep a base query in a variable and branch from it. where with an operator is split into named methods: WhereEq, WhereGt, WhereLt, WhereNull...
Laravel Rust. A query only runs when awaited, and running it only borrows it, so q.count().await? then q.get().await? works. first/find return Option<T>; add .or_abort(404)? for firstOrFail behaviour.
Watch out. Column names are quoted, so Select("count(*)") reads a column literally named count(*): use SelectRaw (Go) or col("*").count() (Rust) for expressions. Never pass user input as a column name without an allowlist.
An Eloquent model reads its columns from the database at run time. In both ports the model is a plain struct whose field types *are* the casts (nullable = pointer or Option), and mass assignment protection comes from copying only declared fields: an explicit struct literal in Go, a fills = Post input struct in Rust.
typeStatusstring// a named string type is an enum columnconst (
DraftStatus = "draft"PublishedStatus = "published"
)
typePoststruct {
ID int64`json:"id"`UserIDint64`json:"user_id"`Titlestring`json:"title"`StatusStatus`json:"status" db:",default"`// DB default applies when zeroMeta db.JSON[[]string] `json:"meta"`// 'array' castPublishedAt *time.Time`json:"published_at"`// nullable datetimeInternalNotes *string`json:"-"`// $hiddenCreatedAt time.Time`json:"created_at"`UpdatedAt time.Time`json:"updated_at"`
}
// No $fillable: copy the allowed fields from a validated form yourself
post := models.Post{UserID: user.ID, Title: form.Title}
err := model.Create(r, &post) // fills ID, timestamps, defaults
err = model.Update(r, &post, db.Values{"title": "New title"})
post, err = model.Find[models.Post](r, id) // *db.NotFoundError -> 404
Laravel Rust
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Enum)]#[serde(rename_all = "snake_case")]pubenumStatus { Draft, Published } // stored as "draft" / "published"#[model]// derives Clone, Debug, Serialize; table = "posts"pubstructPost {
pub id: i64,
pub user_id: i64,
pub title: String,
#[default]pub status: Status, // DB default when omittedpub meta: Option<serde_json::Value>, // JSON columnpub published_at: Option<Timestamp>, // nullable datetime#[serde(skip)]pub internal_notes: Option<String>, // $hiddenpub created_at: Timestamp,
pub updated_at: Timestamp,
}
// $fillable = a fill struct: only its fields can be written from input#[laravel::input(fills = Post)]#[validate(authenticated)]pubstructNewPost { #[validate(required)]pub title: String }
letmut post = create!(Post { user_id: user.id, ..input }).await?;
update!(post { title: "New title" }).await?;
let post = Post::find_or_fail(id).await?; // 404 if missing
Laravel. Laravel 13 prefers PHP attributes (#[Fillable], #[Hidden], #[Table]) over the old $fillable/$hidden properties; casts() is still a method.
Laravel Go. Table and column names follow Laravel conventions (Post is posts, UserID is user_id); override with a TableName() method or a db:"is_admin" tag. Never validate a request straight into a model struct, or a client could set is_admin.
Laravel Rust.#[model] checks column names and value types at compile time: Post::user_id.eq("x") will not compile. Secrets like PasswordHash and Encrypted<T> refuse to compile unless marked #[serde(skip)].
Tip. Both ports only write what changed: model.Update / update! skip the query, hooks and events when no value differs; when something does change, updated_at is refreshed too.
Eloquent relationships are methods that lazy-load on first access (hello, N+1). In both ports a relationship is a tagged struct field that is never lazy-loaded: you ask for it up front with With/with, or query it explicitly. Go names relationships with strings, Rust with typed descriptors like Post::user.
Laravel
<?php
classPostextendsModel
{
publicfunctionuser(): BelongsTo
{
return$this->belongsTo(User::class);
}
publicfunctioncomments(): HasMany
{
return$this->hasMany(Comment::class);
}
}
// 4 queries total instead of 1 + N + N + N$posts = Post::with(['user', 'comments.user'])->latest()->get();
foreach ($postsas$post) {
echo"{$post->title} by {$post->user->name} ({$post->comments->count()})";
}
$post->comments()->create(['body' => 'First!', 'user_id' => $user->id]);
Laravel Go
typePoststruct {
ID int64`json:"id"`UserIDint64`json:"user_id"`Titlestring`json:"title"`User *User`json:"user,omitzero" model:"belongs_to"`Comments []Comment`json:"comments,omitzero" model:"has_many"`
}
// relationship names are the fields in snake_case; dots nest
posts, err := model.Query[models.Post]().
With("user", "comments.user").
Latest("created_at").
Get(r)
if err != nil {
return web.Fail(err)
}
for _, post := range posts {
fmt.Println(post.Title, "by", post.User.Name, len(post.Comments))
}
// sets post_id for you, like $post->comments()->create()
comment := models.Comment{Body: "First!", UserID: user.ID}
err = model.CreateRelated(r, &posts[0], "comments", &comment)
Laravel Rust
use laravel::model::{BelongsTo, HasMany, create, model};
#[model]pubstructPost {
pub id: i64,
pub user_id: i64,
pub title: String,
#[belongs_to]pub user: BelongsTo<User>,
#[has_many]pub comments: HasMany<Comment>,
}
let posts = Post::query()
.with((Post::user, Post::comments.with(Comment::user)))
.order_by(Post::id.desc())
.get()
.await?;
for post in &posts {
println!("{} by {} ({})", post.title, post.user.name, post.comments.len());
}
let post = &posts[0];
create!(post.comments() { body: "First!", user: &user }).await?;
Laravel Go. A misspelled name like With("coments") panics with the list of real relationships. Use model.Load(r, &user, "posts") for an already-loaded model and model.Related[models.Post](&user, "posts") to query one.
Laravel Rust. Use BelongsTo<Option<User>> / HasOne<Option<Profile>> when the related row may not exist; a non-optional relationship errors if it is missing. post.user.is_loaded() and try_loaded() avoid panics on unloaded fields.
Tip. Counts work like withCount: Go WithCount("comments") fills a CommentsCount field, Rust .with_count(Post::comments) is read with post.comments.count().
Watch out. Unloaded relationship fields are left out of JSON (omitzero in Go, automatic in Rust), so forgetting With gives a missing key, not a lazy query.
The Blueprint API is nearly identical (foreignId()->constrained() becomes ForeignID().Constrained() / foreign_id().constrained()). The big change: both ports' migrations are forward-only functions with no down() and no migrate:rollback, and they compile into the binary so production runs them without source files.
// laravel make:migration create_comments_table// database/migrations/2026_12_01_090000_create_comments_table.gopackage migrations
import (
"context""go.laravel.com/schema"
)
funccreateCommentsTable(ctx context.Context) error {
return schema.Create(ctx, "comments", func(table *schema.Blueprint) {
table.ID()
table.ForeignID("post_id").Constrained().CascadeOnDelete()
table.ForeignID("user_id").Constrained()
table.Text("body")
table.Boolean("approved").Default(false)
table.Timestamps()
})
}
// make:migration also appends it to All in database/migrations/migrations.go:// {Name: "2026_12_01_090000_create_comments_table", Run: createCommentsTable},// laravel migrate | migrate:status | migrate:fresh --seed (no rollback)
Laravel Rust
// laravel make:migration create_comments_table// database/migrations/2026_12_01_090000_create_comments_table.rsuse laravel::db::AnyTransaction;
pubasyncfnmigrate(tx: &mutAnyTransaction<'_>) -> laravel::Result<()> {
tx.schema()
.create("comments", |table| {
table.id();
table.foreign_id("post_id").constrained().cascade_on_delete();
table.foreign_id("user_id").constrained();
table.text("body");
table.boolean("approved").default(false);
table.timestamps();
})
.await
}
// src/app.rs embeds every file in the folder at compile time:// laravel::db::migrations!(fn migrations = "database/migrations");// laravel migrate | migrate:status | migrate:fresh --seed (no rollback)
Watch out. No down() in either port. To undo a change in production, write a new migration (for example one that drops the column). Never edit or rename a migration that has run: an edited one will not re-run and a renamed one runs twice.
Laravel Go. Go cannot discover functions in a folder at run time, so migrations are listed in All (make:migration does it). Set NoTransaction: true on an entry for statements like a concurrent index build.
Laravel Rust. Take &AnyConnection instead of &mut AnyTransaction to run a migration outside a transaction. Call tx.schema() again for each extra statement; each one runs when awaited.
Tip. Each migration plus its migrations row runs in one transaction, so a failure on PostgreSQL or SQLite leaves nothing half-applied (MySQL still commits on DDL).
Factories and seeders do the same job as in Laravel. In Go a factory is a package variable built with factory.New and states are plain functions; in Rust a factory is a #[factory(Post)] struct next to the model whose definition is a create! expression, so a new required column breaks the factory at compile time.
Laravel Go. In tests use the client: client.Create(factories.User), client.CreateMany(3, factories.Post.For("user", user)). In seeders call the factory's own Create/CreateMany(ctx, n), which return an error.
Laravel Rust.has(User::posts, Comment::factory()) is a compile error because the factory type must match the relationship. Call other seeders as plain async functions: roles().await?;.
Tip. Both ports wrap the whole db:seed run in one transaction, and migrate:fresh --seed works as in Laravel. Use InsertMany (Go) or .insert() (Rust) for thousands of rows you do not need back.
->paginate(15) works the same way everywhere and produces the same JSON (data, current_page, last_page, links, ...). Go is explicit about where the page number comes from (r.Page(15) reads ?page=); Rust reads it from the current request for you.
Laravel
<?php
publicfunctionindex()
{
$posts = Post::with('user')
->whereNotNull('published_at')
->latest('published_at')
->paginate(15); // reads ?page= from the requestreturn$posts; // {"data": [...], "current_page": 1, "links": [...], ...}
}
// cheaper variantsPost::latest()->simplePaginate(15); // no count queryPost::latest()->cursorPaginate(15); // ?cursor=, no offset$posts->items();
$posts->total();
$posts->nextPageUrl();
use laravel::pagination::Paginator;
use laravel::prelude::*;
usecrate::models::Post;
pubasyncfnindex() -> laravel::Result<Json<Paginator<Post>>> {
let posts = Post::query()
.with(Post::user)
.filter(Post::published_at.is_not_null())
.order_by(Post::published_at.desc())
.paginate(15) // page comes from ?page= automatically
.await?;
Ok(Json(posts))
}
// cheaper variants: .simple_paginate(15), .cursor_paginate(15)// posts.items(), posts.total(), posts.next_page_url()// .map(|post| PostSummary { id: post.id, title: post.title })
Tip. Always order a paginated query so rows stay on the same page between requests. Cursor pagination needs a unique order (add id as a tie-breaker).
Laravel Go. Table queries need the row type: db.Table("subscribers").OrderBy("email").Paginate[Subscriber](r, r.Page(15)). Model queries do not.
Laravel Rust. The handler return type names the paginator (Json<Paginator<Post>>), so simple_paginate returns a SimplePaginator and cursor_paginate a CursorPaginator.
All three ship session auth with "remember me", and let you write your own login form. Auth::attempt becomes auth.Attempt (Go) or auth.attempt on an Auth<User> extractor (Rust), and a wrong password comes back as a normal validation error on email. Neither port includes Sanctum: API tokens are a request guard you write.
Laravel
<?php
// routes/web.phpRoute::post('/login', [SessionController::class, 'store'])->middleware('guest');
Route::middleware('auth')->get('/dashboard', DashboardController::class)
->name('dashboard');
// SessionControllerpublicfunctionstore(Request$request)
{
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
]);
if (! Auth::attempt($credentials, $request->boolean('remember'))) {
throwValidationException::withMessages([
'email' => 'These credentials do not match our records.',
]);
}
$request->session()->regenerate();
returnredirect()->intended(route('dashboard'));
}
// Auth::user(), Auth::logout(); API tokens: Sanctum + auth:sanctum
use laravel::auth::Auth;
use laravel::hash::Password;
use laravel::prelude::*;
#[laravel::input]#[validate(anyone)]pubstructLogin {
#[transform(lowercase)]#[validate(required, email)]
email: String,
#[validate(required)]
password: Password, // never Debug-printed into logs#[serde(default)]
remember: bool,
}
pubasyncfnlogin(auth: Auth<User>, form: Valid<Login>) -> laravel::Result<Redirect> {
// wrong password = validation error on "email"
auth.attempt(&form.email, &form.password).remember(form.remember).await?;
Ok(Redirect::intended(dashboard::show, ()))
}
// routes: route.middleware(Authenticate).group(|route| { ... });// handlers: Authenticated(user): Authenticated<User> logout: auth.logout().await?
Laravel Go. The session guard is the auth.Session[models.User]{} middleware appended to the web group in bootstrap/app.go. For bearer tokens write func(r *web.Request) (*models.User, error) and protect routes with auth.Via(apitokens.User).
Laravel Rust. Your User derives Authenticatable. For bearer tokens implement RequestGuard on a #[singleton] service and use Authenticate::via::<ApiTokens>(); Authenticated<User> then works on those routes too.
Watch out. There is no Sanctum, Fortify or Breeze-style package in v0.2: token issuing and storage is your code. The docs recommend storing a SHA-256 hash of each token, not the token.
Tip. Guest redirects need a route namedlogin in Go; in Rust you mark the login page so Authenticate knows where to send guests. JSON requests get a 401 instead.
Laravel looks up a policy method by string ('update'). The ports pass the ability itself, so a typo or a wrong model type is a compile error. Go abilities are functions returning auth.Ability; Rust policies are an impl block marked #[policy]. There is no separate Gate::define: an ability without a record plays that role.
Laravel
<?php
classPostPolicy// auto-discovered for Post
{
publicfunctionupdate(User$user, Post$post): bool
{
return$user->id === $post->user_id;
}
publicfunctiondelete(User$user, Post$post): Response
{
return$user->id === $post->user_id
? Response::allow()
: Response::deny('You do not own this post.');
}
}
// a gate: an ability with no modelGate::define('view-admin', fn (User$user) => $user->is_admin);
// in a controllerGate::authorize('update', $post); // 403 if denied$canDelete = $request->user()->can('delete', $post);
Laravel Go
// policies/post.go: plain functions, nothing to registerfuncUpdatePost(post *models.Post) auth.Ability[models.User] {
returnfunc(_ context.Context, user *models.User) error {
return auth.Allow(user.ID == post.UserID)
}
}
funcDeletePost(post *models.Post) auth.Ability[models.User] {
returnfunc(_ context.Context, user *models.User) error {
if user.ID != post.UserID {
return auth.Deny("You do not own this post.")
}
returnnil
}
}
// instead of Gate::define: an ability that takes no recordfuncViewAdmin() auth.Ability[models.User] {
returnfunc(_ context.Context, user *models.User) error {
return auth.Allow(user.IsAdmin)
}
}
// in a handlerif err := auth.Authorize(r, policies.UpdatePost(&post)); err != nil {
return web.Fail(err) // 403 with the denial message
}
canDelete, err := auth.Can(r, policies.DeletePost(&post))
Laravel Rust
use laravel::auth::{Access, policy};
pubstructPostPolicy;
#[policy]implPostPolicy {
pubfnupdate(user: &User, post: &Post) -> bool {
user.id == post.user_id
}
pubfndelete(user: &User, post: &Post) -> Access {
if user.id == post.user_id {
Access::allow()
} else {
Access::deny("You do not own this post.")
}
}
}
pubasyncfnedit(user: Authenticated<User>, post: Post) -> laravel::Result<Json<Post>> {
user.authorize(PostPolicy::update, &post).await?; // 403 via ?let _can_delete = user.can(PostPolicy::delete, &post).await?;
Ok(Json(post))
}
// no-record ability: user.authorize(PostPolicy::create, ()).await?
Tip. Hide existence with a 404 instead of a 403: auth.DenyAsNotFound() in Go, Access::deny_as_not_found() in Rust (like Response::denyAsNotFound()).
Laravel Go. Guests are denied before an auth.Ability runs. Return auth.GuestAbility[models.User] to decide for guests yourself (the user is then nil). For Laravel's before(), wrap abilities in an orAdmin(...) helper.
Laravel Rust. Form inputs can authorize via a policy: #[validate(authorize(PostPolicy::update, route("post")))], the Rust version of FormRequest::authorize(). Policy methods may be async and return laravel::Result<Access> when they need the database.
Watch out. Neither port documents a can: route middleware or a string-keyed Gate facade in v0.2: call Authorize/authorize in the handler or the input type.
Same model as Laravel: the web group starts a session, encrypts cookies and checks CSRF tokens; the api group does none of that. Go reads typed values with Value[T], Rust deserializes into whatever type you annotate. CSRF in all three first trusts the browser's Sec-Fetch-Site header, then falls back to the _token / X-XSRF-TOKEN.
Laravel
<?php
publicfunctionupdate(Request$request)
{
$theme = $request->session()->get('theme', 'light');
$request->session()->put('theme', 'dark');
returnredirect('/settings')
->with('status', 'Theme saved!') // flash
->withCookie(cookie('theme', 'dark', 60 * 24 * 30)); // minutes
}
$theme = $request->cookie('theme'); // decrypted on web routes// CSRF: PreventRequestForgery is in the web group// Blade: <form method="POST"> @csrf ... </form>// bootstrap/app.php
->withMiddleware(function (Middleware$middleware): void {
$middleware->preventRequestForgery(except: ['stripe/*']);
})
Laravel Go
funcShow(r *web.Request) *web.Response {
theme, ok := r.Session().Value[string]("theme") // typed readif !ok {
theme = "light"
}
if c, err := r.Cookie("theme"); err == nil { // decrypted on web routes
theme = c.Value
}
return web.Text("Theme: " + theme)
}
funcUpdate(r *web.Request) *web.Response {
r.Session().Put("theme", "dark")
r.Session().Flash("status", "Theme saved!")
return web.Redirect("/settings").
WithCookie(cookie.New("theme", "dark", 30*24*time.Hour))
}
// CSRF: ValidateCSRFToken is in the web group; templates use {{csrfField}}// bootstrap/app.goMiddleware: func(m *laravel.Middleware, cfg *config.Config) {
m.Replace(middleware.ValidateCSRFToken{Except: []string{"stripe/*"}})
},
Laravel Rust
use laravel::cookie::Cookie;
use laravel::prelude::*;
pubasyncfnshow(request: Request) -> laravel::Result<String> {
let session = request.session()?;
let theme: Option<String> = request.cookie("theme") // decrypted on web routes
.or_else(|| session.get("theme"));
Ok(format!("Theme: {}", theme.as_deref().unwrap_or("light")))
}
pubasyncfnupdate(session: Session) -> Redirect {
session.put("theme", "dark");
session.flash("status", "Theme saved!");
Redirect::to("/settings")
.with_cookie(Cookie::new("theme", "dark").max_age(30.days()))
}
// CSRF: PreventRequestForgery is in the web group; templates use {{ csrf_field() }}// src/app.rs
.with_middleware(|middleware, _| {
middleware.replace(PreventRequestForgery::new().except(["stripe/*"]));
})
Tip. Same env vars as Laravel: SESSION_DRIVER (database, redis, file, cookie, memory), SESSION_LIFETIME, SESSION_SAME_SITE. Axios and Inertia pick up the XSRF-TOKEN cookie automatically in all three.
Laravel Go. Cookies are a standard *http.Cookie; cookie.New, cookie.Session and cookie.Forever just set the attributes. r.Session() panics on a route without StartSession (check r.HasSession() in shared middleware).
Laravel Rust. Taking a Session argument on an api route fails the request; use request.session()? when the route may not have one. To skip CSRF on one route: .without_middleware::<PreventRequestForgery>().
Laravel. Laravel 13 renamed VerifyCsrfToken/ValidateCsrfToken to PreventRequestForgery, which adds the Sec-Fetch-Site origin check that both ports also use.
Laravel throws exceptions and a central handler reports and renders them. Go has no exceptions: a handler returns web.Fail(err), and an error type picks its own HTTP status with a StatusCode() method. Rust returns laravel::Result and uses ?, with #[derive(Status)] for the status. Logging uses each language's standard tool: slog in Go, tracing in Rust.
Laravel
<?php
classPostLockedextendsException {}
// bootstrap/app.php
->withExceptions(function (Exceptions$exceptions): void {
$exceptions->report(function (PostLocked$e) {
// send to your error tracker...
});
$exceptions->render(function (PostLocked$e, Request$request) {
returnresponse()->json(['message' => $e->getMessage()], 409);
});
})
// in a controllerpublicfunctionpublish(Post$post)
{
throw_if($post->locked, newPostLocked("Post {$post->id} is locked"));
abort_if($post->user_id !== auth()->id(), 403);
Log::info('Post published.', ['post' => $post->id]);
returnback();
}
Laravel Go
// the error type carries its status: no render() registration neededtypePostLockedErrorstruct{ ID int64 }
func (e *PostLockedError) Error() string { return fmt.Sprintf("post %d is locked", e.ID) }
func (e *PostLockedError) StatusCode() int { return http.StatusConflict }
funcPublish(r *web.Request) *web.Response {
post, err := model.FromRoute[models.Post](r, "post") // 404 if missingif err != nil {
return web.Fail(err)
}
if post.Locked { // assumes a boolean "locked" columnreturn web.Fail(&PostLockedError{ID: post.ID}) // 409
}
if post.UserID != r.User[models.User]().ID {
return web.Abort(http.StatusForbidden) // abort(403)
}
slog.InfoContext(r, "Post published.", "post", post.ID) // Log::inforeturn web.Back()
}
// bootstrap/app.go: Errors: web.Errors{Report: reportError} (5xx failures only)
Laravel Rust
use laravel::errors::Status;
use laravel::prelude::*;
#[derive(Debug, thiserror::Error, Status)]#[error("Post {0} is locked")]#[status(409)]pubstructPostLocked(i64);
pubasyncfnpublish(user: Authenticated<User>, post: Post) -> laravel::Result<Redirect> {
if post.locked {
returnErr(PostLocked(post.id).into()); // 409
}
if post.user_id != user.id {
laravel::abort!(403);
}
tracing::info!(post.id = post.id, "Post published");
Ok(Redirect::back())
}
// src/app.rs: reporters only see 5xx failures, never a 409 like PostLockedApplication::configure().with_errors(|errors, _| {
errors.report_all(|error| {
// send to your error tracker...
});
})
Laravel Go. Add context with fmt.Errorf("loading post %d: %w", id, err); the wrapped error keeps its status, so a wrapped 404 is still a 404. Go errors have no stack, so Laravel logs a location=file.go:42 field for you.
Laravel Rust..context("...") / .with_context(|| ...) from the prelude add log context without changing the status. Map a foreign error type to a status with errors.status::<sqlx::Error>(503) in with_errors.
Tip. Logging is configured like Laravel: LOG_CHANNEL=stderr,daily, LOG_LEVEL, plus LOG_FORMAT=json. Every line is tagged with the request ID automatically; in Go only if you use the ...Context slog functions.
Watch out. Unlike Laravel, the ports never report 4xx errors (a 409 is an "expected outcome"), so the report hook only sees 5xx failures. With APP_DEBUG=false those show "Server Error" unless raised on purpose with web.Abortf (Go) or laravel::abort_with (Rust).
The Storage facade becomes the storage package/module with the same disks (local, public, s3) and FILESYSTEM_DISK. An upload is a typed field on the validated input (*web.Upload / UploadedFile) whose Store method saves it under a random name and returns the path, like $file->store().
use laravel::http::UploadedFile;
use laravel::model::update;
use laravel::prelude::*;
#[laravel::input]#[validate(authenticated)]pubstructUpdateAvatar {
#[validate(required, image, max_kilobytes(2048))]
avatar: UploadedFile,
}
pubasyncfnupdate(
Authenticated(mut user): Authenticated<User>,
Valid(form): Valid<UpdateAvatar>,
) -> laravel::Result<Redirect> {
let path = form.avatar.store("avatars").disk("public").await?;
update!(user { avatar_path: path }).await?; // User must have this columnOk(Redirect::back())
}
// use laravel::storage;// storage::put("reports/monthly.csv", csv).await?;// storage::get("reports/monthly.csv").await?;// storage::disk("public")?.url(&path).await?;
Laravel Go. Extra disks are typed config: cfg.Filesystems.Disks["documents"] = config.LocalDisk{Root: "storage/app/documents"} (also config.S3Disk, config.CloudDisk). Every call takes a context (r or ctx).
Laravel Rust. Every storage call is async and returns a Result, so it ends in .await?. Omit .disk(..) to use the default disk; store_as(dir, name) picks the filename.
Watch out.storage.Get / storage::get read the whole file and refuse files over 8 MiB by default. Use ReadStream / get_with_limit for big files, unlike PHP's memory-limit-bound Storage::get.
Services, queues, events, realtime, caching, workflows and shipping to production. Most Laravel concepts carry over almost name for name, but Laravel Go and Laravel Rust run as one long-lived binary, so "per request" state, background work and deployment work differently from PHP-FPM.
Laravel resolves classes from a reflection-based container that service providers fill. Laravel Go has no container: you build one Services struct at startup and read it back with services.From(ctx). Laravel Rust keeps a real container, but services are registered by type and injected as Inject<T> handler arguments.
Laravel
<?php
// app/Providers/AppServiceProvider.phppublicfunctionregister(): void
{
$this->app->singleton(SpamChecker::class, fn () => newSpamChecker(
key: config('services.spam.key'),
));
}
// Or on the class itself (Laravel 13): #[Singleton]// app/Http/Controllers/CommentController.phppublicfunctionstore(Request$request, Post$post, SpamChecker$spam)
{
// $spam is resolved and injected by the containerabort_if($spam->isSpam($request->input('body')), 422);
$post->comments()->create($request->only('body'));
returnback();
}
// Anywhere else: app(SpamChecker::class)
Laravel Go
// services/services.gotypeServicesstruct {
Spam *spam.Checker// your own client, built once
}
funcNew(env *config.Env, app *laravel.App) Services {
returnServices{Spam: spam.NewChecker(env.String("SPAM_API_KEY", ""))}
}
funcFrom(ctx context.Context) *Services {
return laravel.ServicesOf[*Services](ctx)
} // bootstrap/app.go: Services: laravel.BuildServices(services.New)// handlers/comments/comments.gofuncStore(r *web.Request) *web.Response {
var form struct {
Bodystring`json:"body"`
}
if err := r.BindInto(&form); err != nil {
return web.Fail(err)
}
isSpam, err := services.From(r).Spam.Check(r, form.Body)
if err != nil {
return web.Fail(err)
}
if isSpam {
return web.Abortf(422, "Looks like spam.")
}
return web.Back() // after saving the comment
}
Laravel Rust
// src/services/spam.rsuse laravel::config::Section;
use laravel::container::singleton;
#[derive(Clone, Section)]pubstructSpamConfig {
#[env("SPAM_API_KEY", required)]pub key: String,
}
pubstructSpamChecker { key: String }
#[singleton]// discovered automatically, built on first useasyncfnspam_checker(config: Section<SpamConfig>) -> laravel::Result<SpamChecker> {
Ok(SpamChecker { key: config.key.clone() })
}
// src/http/handlers/comments.rs (with use laravel::prelude::*)pubasyncfnstore(
spam: Inject<SpamChecker>,
Valid(form): Valid<StoreComment>, // a #[laravel::input] struct
) -> laravel::Result<Redirect> {
if spam.is_spam(&form.body).await? {
returnErr(laravel::abort_with(422, "Looks like spam."));
}
// Save the comment...Ok(Redirect::back())
}
Laravel Go. There is no app() or auto-wiring. Dependencies are plain constructor arguments inside services.New, so the Go compiler catches a missing dependency. Laravel's own subsystems (DB, cache, mail, queue) are reached through their packages (cache.Remember(r, ...)), not through Services.
Laravel Rust.app.singleton(..) and app.bind(..) in src/app.rs mirror Laravel's singleton and bind. singleton_as registers under a trait (Inject<dyn Geocoder>), like binding an interface to an implementation. Code without handler arguments calls laravel::resolve::<T>().await.
Watch out. In both ports a singleton lives for the whole process, like under Octane. Never keep the current user or request data in a service's fields; pass it to the method instead.
Tip. Both docs say the same thing: stateless domain logic does not need a registered service. Write plain functions (orders.Place(ctx, ...) / pub async fn place(..)) and keep the container for clients, config and shared state.
In Laravel, Context is a facade that adds values to every log line and to queued jobs. In Go, "context" is the standard context.Context that every function takes first: it carries the application, log values and cancellation. In Rust it is a Tokio task-local that helpers such as laravel::context::get read implicitly.
Laravel
<?php
// app/Http/Middleware/IdentifyTenant.phppublicfunctionhandle(Request$request, Closure$next): Response
{
$tenant = Str::before($request->getHost(), '.');
Context::add('tenant', $tenant); // on every log line + queued jobreturn$next($request);
}
// Later in the request, or in a job it dispatched:$tenant = Context::get('tenant');
Log::info('Post published', ['post' => $post->id]); // carries tenant// Memoize for the rest of the request:$count = once(fn () => Post::count());
Laravel Go
funcIdentifyTenant(r *web.Request, next web.Next) *web.Response {
tenant, _, _ := strings.Cut(r.Host, ".")
ctx := log.With(r, "tenant", tenant) // returns a NEW contextreturnnext(r.WithContext(ctx))
}
// Later: any func that received ctx (handler, job, listener...)funcPublish(ctx context.Context, post *models.Post) error {
if tenant, ok := log.Value(ctx, "tenant"); ok { // like Context::get
post.Tenant = tenant.String()
}
slog.InfoContext(ctx, "Post published.", "post", post.ID) // carries tenantreturnnil
}
// Memoize per request (models/post.go):varPostCount = laravel.Once(func(ctx context.Context) (int, error) {
return model.Query[Post]().Count(ctx)
})
Laravel Rust
use laravel::http::{Next, middleware};
use laravel::prelude::*;
#[middleware]pubasyncfnidentify_tenant(request: Request, next: Next) -> Response {
let tenant = request.host().split('.').next().unwrap_or_default().to_owned();
laravel::context::add("tenant", tenant); // on every log line + job
next.run(request).await
}
// Later in the request, or in a job it dispatched:let tenant: Option<String> = laravel::context::get("tenant");
tracing::info!(post.id = post.id, "Post published"); // carries tenant// Memoize per request:#[laravel::once]pubasyncfnpost_count() -> laravel::Result<u64> {
Post::query().count().await
}
Laravel Go. Give your own functions a ctx context.Context first parameter, not a *web.Request, so they also run from jobs, commands and tests. In a handler, ris the context. Passing context.Background() makes Laravel helpers panic with a hint.
Laravel Go. The Go context also carries cancellation: when the visitor leaves or a route timeout passes, queries and HTTP calls that received r stop early. PHP has no equivalent.
Laravel Rust. Task-locals do not cross tokio::spawn. Use laravel::task::spawn (or task::background) so the spawned work keeps the context and tracing span.
Tip. Hidden values exist in all three: Context::addHidden, Go log.WithHidden / log.Hidden[T], Rust context::add_hidden / get_hidden. They travel to jobs but stay out of logs.
All three share the same cache API shape: remember, flexible, put, forget, counters and locks, over memory, database or Redis stores. Go and Rust need the value type spelled out and store values as JSON; neither has cache tags in v0.2.
Laravel
<?php
useIlluminate\Support\Facades\Cache;
$popular = Cache::remember('posts:popular', now()->addMinutes(10), function () {
returnPost::whereNotNull('published_at')
->orderByDesc('views')->take(10)->get();
});
// Fresh for 5 min, then served stale while it refreshes, up to 10 min:$count = Cache::flexible('posts:count', [300, 600], fn () => Post::count());
Cache::forget('posts:popular'); // after publishing a postCache::increment('posts:views:today');
use laravel::cache;
use laravel::prelude::*;
let popular: Vec<Post> = cache::remember("posts:popular", 10.minutes(), async || {
Post::query()
.filter(Post::published_at.is_not_null())
.order_by(Post::views.desc())
.limit(10)
.get()
.await
})
.await?;
let count: u64 = cache::flexible("posts:count", 5.minutes(), 10.minutes(), async || {
Post::query().count().await
})
.await?;
cache::forget("posts:popular").await?;
let views = cache::increment_or_add("posts:views:today", 1, 1.day()).await?;
Laravel Go.cache.Get[string](r, key) needs the type in brackets, because Go cannot infer it from a key. Every function takes the context first (r in a handler, ctx in a job).
Laravel Rust. The closure returns laravel::Result, so ? works inside it, and an error is never cached. The annotation on the let (Vec<Post>) picks the type to decode.
Watch out. No cache tags in either port as of v0.2: use key prefixes and forget each key. And the memory store is per process, so cache:clear cannot empty a running server's memory store.
Tip. Values are JSON. If a deploy changes a struct's shape, remember/flexible treat the old value as a miss and recompute it, while a plain get returns a decode error.
Same model everywhere: a job is a serializable value with a handle method, dispatched to a connection and queue, and run by queue:work. Laravel 13 configures retries with attributes; Go uses a JobOptions method; Rust uses options on the #[job] attribute.
Laravel
<?php
namespaceApp\Jobs;
useApp\Models\Post;
useApp\Services\ImageRenderer;
useIlluminate\Contracts\Queue\ShouldQueue;
useIlluminate\Foundation\Queue\Queueable;
useIlluminate\Queue\Attributes\{Backoff, Timeout, Tries};
#[Tries(3)]#[Backoff([10, 60])]
#[Timeout(120)]classGenerateSocialImageimplementsShouldQueue
{
useQueueable;
publicfunction__construct(publicPost$post) {} // stores only the idpublicfunctionhandle(ImageRenderer$renderer): void
{
$renderer->render($this->post);
}
}
// In a controller:GenerateSocialImage::dispatch($post)->onQueue('images')->delay(now()->addMinutes(5));
Laravel Go
// jobs/generate_social_image.gotypeGenerateSocialImagestruct {
Post models.Post`queue:"model"`// stores only the ID, reloads before Handle
}
func (GenerateSocialImage) JobOptions() queue.Options {
return queue.Options{
Tries: 3,
Backoff: []time.Duration{10 * time.Second, time.Minute},
Timeout: 2 * time.Minute,
}
}
func (j GenerateSocialImage) Handle(ctx context.Context) error {
return services.From(ctx).Images.Render(ctx, j.Post)
}
// jobs/jobs.go: var All = []any{GenerateSocialImage{}}// In a handler:
_, err := queue.OnQueue("images").
Delay(5*time.Minute).
Dispatch(r, jobs.GenerateSocialImage{Post: post})
Laravel Rust
// src/jobs/generate_social_image.rsuse laravel::prelude::*;
use laravel::queue::{Queueable, job};
#[derive(Queueable)]pubstructGenerateSocialImage {
pub post: Post, // stores only the key, reloads before handle
}
#[job(tries = 3, backoff = [10.seconds(), 1.minutes()], timeout = 2.minutes())]
implGenerateSocialImage {
asyncfnhandle(self, images: Inject<ImageRenderer>) -> laravel::Result<()> {
images.render(&self.post).await
}
}
// In a handler:GenerateSocialImage { post }
.dispatch()
.on_queue("images")
.delay(5.minutes())
.await?;
Laravel Go. Go cannot discover types by reflection over files, so every job type is listed in jobs.All (laravel make:job does it for you). A model field tagged queue:"model" behaves like SerializesModels.
Laravel Rust. Jobs are discovered automatically; nothing to register. Add #[serde(default)] to new fields so jobs already on the queue still deserialize.
Watch out. Timeouts cannot kill code from outside in either language. Go ends the job's ctx, so pass ctx to every query and call; Rust cancels at the next .await, so move CPU-heavy work to task::spawn_blocking.
Tip. No ShouldBeUnique in v0.2; the closest is debounced jobs (DebounceFor / debounce_for), which Laravel 13 also has as #[DebounceFor]. Job names default to the type path, so set JobName() / #[job(name = ..)] before you move a job.
An event is a plain data type and listeners react to it, synchronously or on the queue. Laravel discovers listeners by type-hint; Go lists them in listeners.All; Rust discovers #[listener] functions at boot.
Laravel Go. A listener of an interface type receives every event that implements it (one audit listener for all auditable events), and a listener of any receives everything. That replaces wildcard listeners.
Laravel Rust. Events own their data (String, not &str), so clone what listeners need from the request. Do not also pass a #[listener] function to events.listen, or it runs twice.
Tip. Same failure rule in all three: a listener error stops the remaining listeners and bubbles up. Inside a DB transaction the ports always run listeners after commit (Laravel only does so with ShouldDispatchAfterCommit). For fire-and-forget, Go has laravel.Background and Rust has dispatch_background() (in memory, not retried).
The scheduler API is almost identical: closures, commands and queued jobs with fluent frequencies, withoutOverlapping and onOneServer, driven by one cron entry running schedule:run. Go defines it in commands/schedule.go; Rust in a #[schedule::tasks] function.
Laravel Go.Call takes the task name as its first argument (it keys the locks and schedule:list). OnOneRunner is the Go spelling of onOneServer.
Laravel Rust. Scheduled functions may take Inject<T> and Section<T> arguments like handlers. Callbacks that use without_overlapping must have a .name(..).
Watch out. Both ports evaluate every schedule in UTC, with no per-task timezone(); for local times, schedule both candidate UTC hours and check the hour in When / when. Overlap and one-runner locks need a shared cache store (database or redis), not memory.
Tip. On Laravel Cloud you skip the cron entry in all three: enable the Scheduler toggle and Cloud runs schedule:run every minute.
The Go and Rust "tasks" pages cover running work concurrently inside one request, time limits, and fire-and-forget work after the response. Laravel's closest equivalents are Concurrency::run, which runs closures in extra PHP processes, and defer(). In Go and Rust the same work runs on goroutines or futures inside the one process.
use laravel::db::{self, col};
use laravel::http::client;
use laravel::prelude::*;
use laravel::task;
use serde_json::json;
pubasyncfnstats(Params(id): Params<i64>) -> laravel::Result<Json<serde_json::Value>> {
let (comments, likes) = task::try_join!( // futures, no .await
db::table("comments").filter(col("post_id").eq(id)).count(),
db::table("likes").filter(col("post_id").eq(id)).count(),
)?;
task::background(asyncmove { // like defer()
client::post("https://stats.example.com/views")
.json(json!({ "post_id": id }))
.await?;
Ok(())
})?;
Ok(Json(json!({ "comments": comments, "likes": likes })))
}
Laravel Go. Prefer task.Run, task.Both, task.Map (bounded concurrency) and task.Timeout over a bare go statement: they pass the app context, turn panics into errors, and cancel siblings when one fails.
Laravel Rust. Use task::spawn, not tokio::spawn, so the new task keeps the application context. task::timeout(3.seconds(), fut).await?? unwraps the timeout and the inner result.
Watch out. Background work is in memory and not retried in any of the three. A crash loses it. Anything that must happen (charging a card, sending a receipt) belongs on the queue.
Tip. Both ports also have ticks: a function that runs every N seconds inside each server and worker process (for example flushing buffered view counts). PHP-FPM has no equivalent because nothing lives between requests.
All three broadcast events over the Pusher protocol to Reverb, authorize private channels with a callback at POST /broadcasting/auth, and use Laravel Echo in the browser. The big difference: the Go and Rust reverb:start server is for local development only; production uses managed Reverb on Laravel Cloud.
// events/comment_posted.gotypeCommentPostedstruct {
PostIDint64`json:"post_id"`// json tags shape the payloadBodystring`json:"body"`
}
func (e CommentPosted) BroadcastOn() []broadcast.Channel {
return []broadcast.Channel{broadcast.Private(fmt.Sprintf("posts.%d", e.PostID))}
}
// routes/channels.go (Routes.Channels in bootstrap/app.go)funcChannels(channel *routing.Channels) {
channel.Private("posts.{post}", func(r *web.Request, user *models.User) (bool, error) {
post, err := model.FromRoute[models.Post](r, "post")
if err != nil {
returnfalse, err
}
return post.UserID == user.ID, nil
})
}
// Dispatch: event.Dispatch(r, events.CommentPosted{PostID: p.ID, Body: c.Body})// Local: laravel reverb:start (production: managed Reverb on Cloud)
Laravel Rust
// src/events/mod.rsuse laravel::event::Event;
#[derive(Event)]#[event(broadcast(private = "posts.{post_id}"))]pubstructCommentPosted {
pub post_id: i64,
pub body: String,
}
// src/routes/channels.rsuse laravel::broadcast::Channels;
use laravel::prelude::*;
pubfnroutes(channel: &mutChannels) {
channel.private("posts.{post}", can_listen);
}
asyncfncan_listen(post: Post, user: Authenticated<User>) -> bool {
post.user_id == user.id // post is bound from {post} like a route
}
// Dispatch: CommentPosted { post_id, body }.dispatch().await?;// Local: laravel reverb:start (production: managed Reverb on Cloud)
Laravel Go. Any event with a BroadcastOn method broadcasts; optional BroadcastWith, BroadcastAs and BroadcastWhen methods match Laravel's broadcastWith, broadcastAs and broadcastWhen. A failed broadcast does not stop the listeners.
Laravel Rust. Channels are declared in #[event(broadcast(..))] with {field} placeholders. Authenticated<User> in a channel callback rejects guests with a 403 before your code runs.
Watch out. The Go/Rust reverb:start runs in one process with state in memory and does not scale. The docs point production at managed Reverb on Laravel Cloud; self-hosting PHP Reverb (or another Pusher-compatible server) is not covered by the port docs.
Tip. The frontend is unchanged: Echo, useEcho and presence channels work the same, because all three speak the Pusher protocol. Broadcasts go through the queue by default, so run a worker.
All three throttle routes with middleware and expose a limiter for your own code, counting per user or per IP in the cache. Laravel names limiters with RateLimiter::for and uses fixed windows; the ports attach a Throttle value directly to the route and use a token bucket.
Laravel
<?php
// AppServiceProvider::boot()RateLimiter::for('comments', function (Request$request) {
returnLimit::perMinute(10)->by($request->user()?->id ?: $request->ip());
});
// routes/web.phpRoute::post('/posts/{post}/comments', [CommentController::class, 'store'])
->middleware('throttle:comments');
// Inside your own code:$sent = RateLimiter::attempt('reports:'.$user->id, 5, function () use ($post) {
// Report the post...
}, decaySeconds: 60);
abort_unless($sent, 429);
Laravel Go
// routes/web.go: per user when logged in, else per IP
route.Post("/posts/{post}/comments", comments.Store).
Middleware(middleware.ThrottlePerMinute(10).WithBucket("comments"))
// Inside your own code:funcReport(r *web.Request) *web.Response {
user := r.User[models.User]()
key := fmt.Sprintf("reports:%d", user.ID)
if _, err := rate.Attempt(r, key, rate.PerMinute(5)); err != nil {
return web.Fail(err) // *rate.TooManyAttemptsError -> 429
}
// Report the post...return web.Back()
}
Laravel Rust
use laravel::http::middleware::Throttle;
use laravel::prelude::*;
use laravel::rate_limit::{self, Limit};
pubfnroutes(route: &mutRouter) {
route
.post("/posts/{post}/comments", comments::store)
.middleware(Throttle::per_minute(10).bucket("comments"));
}
// Inside your own code:pubasyncfnreport(user: Authenticated<User>) -> laravel::Result<Redirect> {
let key = format!("reports:{}", user.id);
rate_limit::attempt(&key, Limit::per_minute(5)).await??; // 429 when over// Report the post...Ok(Redirect::back())
}
Watch out. Different algorithm: Laravel (PHP) counts in fixed windows; the ports use a token bucket, so a client may burst its whole allowance and then gets one attempt back every 1/N of the window. Load tests and X-RateLimit-Remaining values will differ.
Laravel Go. Routes with the same limit share a count unless you name a bucket (WithBucket). WithKey replaces "user or IP" with your own key (for example a team), and Globally() shares one count across all clients. Put the throttle afterauth.Via so it can see the user.
Laravel Rust.attempt returns a nested result: the outer one is a cache error, the inner one is TooManyAttempts, so ?? turns a throttled call into the same 429 the middleware sends. .by(..) and .global() mirror Go's WithKey and Globally.
Tip. For per-plan limits, write a middleware that builds a throttle per request and calls its Handle / handle method: the ports' version of returning a Limit from RateLimiter::for.
A notification builds one message per channel and sends it to a notifiable, queued or immediately. In the ports, the mail channel reuses a mailable, and messages are built synchronously without database access, so you load data before sending. Go's Messages also gets no context, so build URLs first; Rust can call route! inside the channel method.
Laravel
<?php
classNewCommentextendsNotificationimplementsShouldQueue
{
useQueueable;
publicfunction__construct(publicComment$comment) {}
publicfunctionvia(object$notifiable): array
{
return ['mail']; // also 'database', 'broadcast', ...
}
publicfunctiontoMail(object$notifiable): MailMessage
{
return (newMailMessage)
->subject('New comment on '.$this->comment->post->title)
->line($this->comment->body)
->action('View post', route('posts.show', $this->comment->post));
}
}
// Queued because of ShouldQueue:$post->author->notify(newNewComment($comment));
Watch out. In v0.2 the ports deliver notifications over mail, SMS, Slack and package channels only. There is no built-in database or broadcast notification channel: store an in-app notification row yourself or broadcast an event.
Laravel Go. Mail views are html/template files; mail::layout gives you the Markdown-mail-style layout. The text version is generated from the HTML view. mail.To(user).Queue(r, m) vs .Send(ctx, m) matches Mail::to()->queue() vs ->send().
Laravel Rust. A notifiable implements ReceivesMail, ReceivesSms or ReceivesSlack. Sending a notification that builds an SMS to a type without ReceivesSms is a compile error, where Go panics at runtime.
Tip. Queued mail is rendered at dispatch time and encrypted with APP_KEY in the ports. A delayed email shows data as of queueing, so dispatch your own job if it must reflect data at send time.
All three wrap the platform client (Guzzle, net/http, reqwest-style) with the same ideas: timeouts, retries, throw/ensure_successful, JSON decoding and fakes for tests. Error statuses are not errors until you ask for that.
use laravel::http::client;
use laravel::prelude::*;
use serde::Deserialize;
#[derive(Deserialize)]pubstructGitHubUser { pub login: String, pub name: String }
pubasyncfnshow(Params(username): Params<String>) -> laravel::Result<String> {
let user: GitHubUser = client::get(format!("https://api.github.com/users/{username}"))
.timeout(3.seconds())
.retry(3, 100.milliseconds()) // non-2xx after retries -> Error::Status
.await?
.json()?; // body is already buffered: no .awaitOk(user.name)
}
// In tests: let github = client::fake(); then assert on it
Laravel Go. Every request takes the context first (r or ctx), so it is cancelled when the visitor leaves and faked in tests. GetJSON[T] fails on non-2xx and decodes in one call; JSON decoding uses encoding/json/v2, which matches field names exactly, so add json tags.
Laravel Rust. Errors are an enum: Error::Connection, Error::Status, Error::Decode, Error::Invalid. Match on it instead of catching ConnectionException vs RequestException. Use Backoff::exponential(..) for growing delays.
Tip. Default timeouts in the ports: 30 s for the response, 10 s to connect. Retries honour Retry-After on 429/503 in both; cap total time with TotalTimeout / total_timeout.
Watch out. The fakes only intercept the framework client. A vendor SDK with its own HTTP client is not faked; point it at a test server instead.
A workflow is a multi-day process written as one function: each step runs once, its result is stored, and the run survives sleeps, deploys and worker restarts. Both ports ship this on top of the queue. Laravel 13 (PHP) has no workflow feature; the closest built-in is a job chain with delays plus status checks you write by hand.
Laravel
<?php
// Laravel 13 has no durable workflows: closest is a delayed job chainuseIlluminate\Support\Facades\Bus;
Bus::chain([
newSendWelcomeEmail($user),
(newSendWritingTips($user))->delay(now()->addDays(3)),
])->dispatch();
classSendWritingTipsimplementsShouldQueue
{
useQueueable;
publicfunction__construct(publicUser$user) {}
publicfunctionhandle(): void
{
if ($this->user->posts()->exists()) {
return; // state checked by hand, no step replay
}
Mail::to($this->user)->send(newWritingTips);
}
}
Laravel Go. Each advance is a queued job that calls Handle from the top; finished steps return their stored result instead of running again. So Handle must be deterministic: do I/O only inside steps, never directly in Handle.
Laravel Rust. Pass the step's future without.await; Laravel awaits it only if the step has not been recorded. Give the workflow a stable name before production, because in-flight runs find their code by name.
Watch out. Workflows need a queue connection that supports delays (database, redis, sqs) plus the workflow tables. With the sync connection a run pauses at the first sleep.
Tip. Beyond sleeps, both ports can wait for an external signal (an approval click or a webhook) through resume tokens and URLs, and you inspect runs with workflow:show. In PHP that usually means status columns plus a sweep command.
The ports' feature flags are Pennant: a feature is a function that decides a scope's first value, which is then stored and reused. Pennant identifies features by string; Go keeps a feature.Define value in a variable and Rust generates a type from a #[flag] function, so a typo fails to compile.
Laravel
<?php
// AppServiceProvider::boot()Feature::define('new-editor', fn (User$user) =>
$user->is_staff || Lottery::odds(1, 100)->choose()
);
// In a controller (scope = the logged-in user):if (Feature::active('new-editor')) {
returnInertia::render('Posts/EditV2', ['post' => $post]);
}
// On a route:Route::get('/editor', EditorController::class)
->middleware(EnsureFeaturesAreActive::using('new-editor'));
Laravel Go
// features/features.govarNewEditor = feature.Define("new-editor", func(ctx context.Context, user *models.User) (bool, error) {
return user.IsStaff || lottery.Odds(1, 100).Draw(ctx), nil
})
varAll = []feature.Definition{NewEditor} // Options.Features in bootstrap/app.go// In a handler (models.User has a FeatureScope() method):
active, err := feature.For(r.User[models.User]()).Active(r, features.NewEditor)
if err != nil {
return web.Fail(err)
}
if active {
return inertia.Render("Posts/EditV2", inertia.Props{"post": post})
}
// On a route (400 when inactive):
route.Middleware(middleware.RequireFeature(features.NewEditor)).Get("/editor", editor.Show)
Laravel Rust
// src/features.rs (discovered automatically)use laravel::feature::flag;
use laravel::lottery::Lottery;
#[flag(name = "new-editor")]pubfnnew_editor(user: &User) -> bool {
user.is_staff || Lottery::odds(1, 100).draw()
}
// In a handler:if user.features().active(features::new_editor).await? {
returnOk(inertia::render("Posts/EditV2", props! { post }));
}
// On a route (400 when inactive):
route
.get("/editor", editor::show)
.middleware(RequireFeature::new(features::new_editor));
Laravel Go. Every feature must be listed in Options.Features; checking an unlisted one panics. The stored name is the string passed to Define, not the variable name, so you can rename the variable safely.
Laravel Rust.#[flag] creates a unit struct named after the function. That is why the docs reference it as features::new_editor: let new_editor = .. would clash with the struct.
Tip. Same store options as Pennant: FEATURE_STORE=database (a features table you migrate) or memory. Values are cached for the rest of the request, and tests pin a value with feature.Fake(..) / feature::fake().
New Go and Rust apps ship the same React + TypeScript + Tailwind + Inertia stack as the Laravel starter kits. Handlers render page components with props, and the root view loads Vite entry points. Only the template language of the root view changes: Blade, Go html/template, or Rust's Jinja-style views.
Laravel Go. Prop keys are sent exactly as written (use camelCase if your components expect it), and json:"-" keeps fields such as the password hash out of props. Large 64-bit IDs can be sent as BigInt with PreserveBigIntegers.
Laravel Rust.props! borrows bare variables and takes ownership of key => value pairs. Deferred closures run after the handler returns, so they cannot borrow locals: capture owned values with async move. Rust has no separate Vite page; Vite is covered in the Inertia and templates guides.
Watch out. Outside debug mode both ports read the Vite manifest (and Rust the root view) once at startup, so restart the binary after npm run build. PHP-FPM picks up a new manifest on the next request.
Tip.laravel dev starts the server, the queue worker and Vite together, like composer run dev. The React side (<Deferred>, useForm, <Link>) is identical, because it is the same Inertia client.
All three send fake requests through the full middleware and routing stack, with fluent assertions, a refreshed database and fakes for queues, mail and HTTP. Tests are plain go test and cargo test, and each test gets its own isolated application, so tests can run in parallel (by default in Rust, with t.Parallel() in Go).
// tests/comments.rsuse laravel::queue;
use laravel::testing::prelude::*;
#[laravel::test]asyncfnstores_a_comment(app: Application) -> laravel::Result<()> {
let queue = queue::fake(); // guard: keep it bound until the endlet user = User::factory().create().await?;
let post = Post::factory().create().await?;
app.post(format!("/api/posts/{}/comments", post.id))
.acting_as(&user)
.json(json!({ "body": "Nice post" }))
.await
.assert_created()
.assert_json_path("data.body", "Nice post");
app.assert_database_has("comments", json!({ "post_id": post.id, "body": "Nice post" }))
.await;
queue.assert_pushed::<NotifyPostAuthor>();
Ok(())
}
Laravel Go. A fake is installed per test client (queuetest.New(client), mailtest.New(client), httpclienttest.New(client)), not globally like Queue::fake(). That is what keeps parallel tests isolated.
Laravel Rust. A test's parameters decide what it gets: no parameters is a plain unit test, an Application parameter boots a fresh app. Each fake() returns a guard; let _ = queue::fake(); drops it immediately.
Tip. Both ports borrow a numbered copy of the test database per package or test (laravel_test_1, ...) and roll each test back in a transaction, so auto-increment IDs keep counting. Assert on returned IDs, not on 1.
Tip. Test env overrides live in code: Go tests/tests.go (laraveltest.Env) and Rust src/testing.rs (with_envs), where Laravel uses phpunit.xml. Queue defaults to sync there too.
A Laravel PHP deploy ships source code to PHP-FPM or Octane, with Forge, Cloud or a script running Composer, caches and migrations. A Laravel Go or Rust deploy ships one compiled binary that is the web server, queue worker, scheduler and CLI in one, next to public/ and storage/.
Laravel
# Forge / your deploy script (Cloud runs the same build + deploy steps)composer install --no-dev --optimize-autoloader
npm ci && npm run build
php artisan migrate --force
php artisan optimize # cache config, routes, views, events# Optional: keep the app in memory instead of PHP-FPMphp artisan octane:start --server=frankenphp --port=8000# Long-running processes (Forge daemons / supervisor)php artisan queue:work --tries=3php artisan queue:restart # after every deploy# cron: * * * * * cd /var/www/blog && php artisan schedule:run
Laravel Go
# Build: assets first, then one binary (views + migrations embedded)npm ci && npm run build
GOOS=linux GOARCH=amd64 go build -o app .
# Ship: app + public/ + storage/ (+ bootstrap/ssr/ if SSR)
./app migrate --force
SERVER_HOST=0.0.0.0 SERVER_PORT=8000 ./app # serve, under systemd
./app queue:work # worker, under systemd
./app queue:restart # after replacing the binary# cron: * * * * * cd /srv/blog && ./app schedule:run >> /dev/null 2>&1# Laravel Cloud build: npm ci && npm run build && go build -o app .# Laravel Cloud deploy: ./app migrate --force
Laravel Rust
# Build a release binary (target/release/<package name>)cargo build --release
npm ci && npm run build
# Ship: binary + public/ + resources/views/ + storage/
./blog migrate --force
SERVER_HOST=0.0.0.0 SERVER_PORT=8000 ./blog # serve, under systemd
./blog queue:work # restart it on every deploy
./blog schedule:interrupt # only with sub-minute tasks# cron: * * * * * cd /srv/blog && ./blog schedule:run >> /dev/null 2>&1# Laravel Cloud build: cargo build --release && npm ci && npm run build# Laravel Cloud deploy: blog migrate --force
Laravel Go. Cross-compile from a Mac with GOOS/GOARCH. Views and migrations are compiled into the binary, so only public/, storage/ and optional bootstrap/ssr/ travel with it. Trust your load balancer with m.Proxies in bootstrap/app.go.
Laravel Rust. Unlike Go, the Rust binary reads resources/views/ at runtime, so ship that directory too. Always deploy a --release build; debug builds are far slower.
Tip. Both servers shut down gracefully on SIGTERM (SERVER_SHUTDOWN_TIMEOUT, default 20 s), answer /up for health checks, and listen on 127.0.0.1:8000 until you set SERVER_HOST=0.0.0.0. There is no Octane step: the binary already stays in memory.
Watch out. Forge is not mentioned in the Go or Rust deployment guides as of v0.2. The documented paths are Laravel Cloud or your own process manager (systemd, containers), and broadcasting in production expects Cloud's managed Reverb.