Skip to content

Routing

David Ciulla edited this page Nov 7, 2026 · 1 revision

Routing

Laravex provides a Laravel-faithful router backed by an ETS table. Routes are registered inside routes/web.ex (and routes/console.ex for Artisan-style commands) and loaded by the application at startup.

Basic Routing

The five most common HTTP verbs are available as top-level functions on Laravex.Routing.Router. Each accepts a path pattern, a handler (an anonymous function or a {Module, :function} tuple), and an optional keyword list of route options.

alias Laravex.Routing.Router

Router.get("/",          fn _req -> View.make("welcome") end)
Router.post("/users",    {App.Http.Controllers.UserController, :store})
Router.put("/users/{id}", {App.Http.Controllers.UserController, :update})
Router.patch("/profile",  {App.Http.Controllers.ProfileController, :update})
Router.delete("/users/{id}", {App.Http.Controllers.UserController, :destroy})

Router.any/3 registers the same handler for all five verbs at once:

Router.any("/ping", fn _req -> Response.json(%{pong: true}) end)

Route Parameters

Wrap parameter names in curly braces. They are merged into request.params and request.route_params before the handler is called:

Router.get("/posts/{id}",          {PostController, :show})
Router.get("/posts/{post}/comments/{comment}", {CommentController, :show})

Inside the controller:

def show(request) do
  id = request.params["id"]
  ...
end

Named Routes

Pass name: in the options list to give a route a name. Use Router.url/2 (or the route/2 helper) to generate a URL by name:

Router.get("/users/{id}", {UserController, :show}, name: "users.show")

# Generate URL:
Router.url("users.show", %{"id" => 42})   # => "/users/42"
# or via helper:
route("users.show", %{"id" => 42})

Requesting a name that has not been defined raises at runtime:

** (RuntimeError) Route [users.show] not defined.

Route Groups

Router.group/2 accepts a keyword list of group options and a zero-arity function. All routes registered inside the function inherit the group options.

Prefix

Router.group([prefix: "admin"], fn ->
  Router.get("/dashboard", {Admin.DashboardController, :index})
  Router.get("/users",     {Admin.UserController,      :index})
end)
# Registers: GET /admin/dashboard, GET /admin/users

Middleware

Router.group([middleware: ["auth"]], fn ->
  Router.get("/account", {AccountController, :show})
end)

Combined

Router.group([prefix: "api/v1", middleware: ["api", "auth:api"]], fn ->
  Router.resource("posts", App.Http.Controllers.Api.PostController)
end)

Groups nest arbitrarily — inner group options are merged on top of outer ones.

Middleware on Individual Routes

You can attach middleware to a single route without a group:

Router.get("/admin", {AdminController, :index}, middleware: ["auth", "can:access-admin"])
Router.get("/feed",  {FeedController, :index},  middleware: ["cache.headers:public;max_age=60"])

String middleware aliases are resolved at dispatch time by Laravex.Http.Middleware.resolve_alias/1. See Middleware for the full alias reference.

Resource Routes

Router.resource/3 registers the standard seven resource routes:

Verb URI Action Route Name
GET /{name} :index {name}.index
GET /{name}/create :create {name}.create
POST /{name} :store {name}.store
GET /{name}/{id} :show {name}.show
GET /{name}/{id}/edit :edit {name}.edit
PUT /{name}/{id} :update {name}.update
DELETE /{name}/{id} :destroy {name}.destroy
Router.resource("posts", App.Http.Controllers.PostController)

Limit the generated actions with :only or :except:

Router.resource("photos", PhotoController, only: [:index, :show])
Router.resource("comments", CommentController, except: [:destroy])

API Resources

Router.api_resource/3 omits the HTML form routes (:create and :edit) and applies the "api" middleware group by default:

Router.api_resource("posts", App.Http.Controllers.Api.PostController)

Model Binding

When a route parameter name matches an App.Models.* module that exposes a find/1 function, the SubstituteBindings middleware automatically resolves the parameter to the loaded model struct:

# Route: GET /users/{user}
# App.Models.User.find(id) is called; result replaces the string param.
Router.get("/users/{user}", fn request ->
  user = request.params["user"]  # %App.Models.User{...}
  View.make("users.show", %{user: user})
end)

If find/1 returns nil, Laravex.Database.ModelNotFoundException is raised and the Error-Handling layer converts it to a 404 response.

Listing Routes

Use the route:list Mix task (via the artisan task) to print all registered routes:

mix artisan route:list

Output columns: METHOD, URI, NAME, MIDDLEWARE.

Route Caching

In production you can serialise the ETS route table to bootstrap/cache/routes.term for fast startup:

mix artisan route:cache   # writes cache
mix artisan route:clear   # deletes cache

The cache is managed by Laravex.Routing.RouteCache. When a cache file is present the application loads it at boot instead of re-evaluating routes/web.ex.

Note: Route closures (anonymous functions) cannot be serialised to the cache file. Convert them to {Module, :function} tuples before caching.

Registering Routes

Your routes/web.ex module must export a register/0 function. It is called automatically by the application during startup:

defmodule Routes.Web do
  alias Laravex.Routing.Router
  alias Laravex.View

  def register do
    Router.get("/", fn _req -> View.make("welcome") end)

    Router.group([middleware: ["auth"]], fn ->
      Router.get("/dashboard", {DashboardController, :index})
      Router.resource("posts", PostController)
    end)
  end
end

Clone this wiki locally