Routing — Laravel

In routes/web.php, Route::get('/address', function () { ... }) pairs a method (the kind of request) and an address with the code that answers it. {id}…

In plain PHP, a page's address is a file name: book-list.php, book-detail.php?id=2, add-book.php. To change an address you rename the file, then search for every link that points to that file, one by one.

Laravel keeps addresses apart from files. Every web address goes in one list, routes/web.php. Each line of that list is called a route. A route pairs one HTTP method (the kind of request, for example GET to open a page or POST to send new data) and one address with the code that answers it.

Picture the clerk at the library door holding a list: "GET /books, to the book list shelf", "POST /books, to the new-book desk". The clerk is Laravel, the list is routes/web.php, each visitor is one request, and the shelf or desk they go to is the code that answers. Every visitor is checked against that list from top to bottom, one line after another, and the first line that matches is the one used.

Basic routes

This is the content of routes/web.php for the Library app in this lesson:

<?php

use Illuminate\Support\Facades\Route;

Route::get('/books', function () {
    return response()->json(['The Rainbow Troops', 'This Earth of Mankind', 'Beauty Is a Wound']);
})->name('books.index');

Route::get('/books/{id}', function (string $id) {
    return response()->json(['id' => $id]);
})->name('books.show');

Route::get('/books/create', function () {
    return 'Add book form';
})->name('books.create');

Route::post('/books', function () {
    return response()->json(['message' => 'created'], 201);
})->name('books.store');

Route::get('/authors/{name?}', function (?string $name = null) {
    return $name ?? 'All authors';
})->name('authors');

Parameters in the address

A part of the address in curly braces is a parameter. Its value is taken from the address and passed to the function. With more than one parameter, the leftmost one in the address goes to the function's first parameter.

Here is the route that answers each request:

Request Route that answers Parameter Answer
GET /books books.index (none) 200 the three titles
GET /books/2 books.show $id = '2' 200 {"id":"2"}
POST /books books.store (none) 201 {"message":"created"}
GET /authors authors $name = null 200 All authors
GET /authors/Andrea authors $name = 'Andrea' 200 Andrea
DELETE /books/2 (none) 405 Method Not Allowed
GET /about (none) 404 Not Found

Order: the first match wins

In the code under Basic routes, /books/{id} is written above /books/create. Before you continue, guess: when you open /books/create, which route answers?

Laravel checks routes in the order they appear in the file. /books/create is checked against books.index first, and it doesn't match. Then it is checked against books.show. {id} matches any segment, create included, so books.show answers with {"id":"create"}. The books.create route below it is never checked.

There are two ways to fix it. A fixed address means an address with no parameter, like /books/create:

// 1. Write the fixed address above the one with a parameter
Route::get('/books/create', ...)->name('books.create');
Route::get('/books/{id}', ...)->name('books.show');

// 2. Or constrain the parameter: id may only be digits
Route::get('/books/{id}', ...)->whereNumber('id')->name('books.show');

->whereNumber('id') is the same as ->where('id', '[0-9]+'). [0-9]+ is a pattern that means "one or more digits". With that digits-only constraint, /books/create and /books/abc no longer match books.show. /books/abc becomes a 404, because no other route matches it.

Route names and route()

With a route name, you don't need to type the address yourself. The function route() builds the full address from that name:

route('books.index');                           // http://127.0.0.1:8000/books
route('books.show', ['id' => 2]);               // http://127.0.0.1:8000/books/2
route('books.show', ['id' => 2, 'tab' => 'reviews']); // http://127.0.0.1:8000/books/2?tab=reviews

Names with dots, like books.index and students.index, are only a naming habit, not folder names.

Seeing every route

php artisan route:list prints every route, sorted by address. The option --except-vendor hides the routes that come with packages, such as the up route:

$ php artisan route:list --except-vendor

  GET|HEAD   authors/{name?} ............. authors › routes/web.php:21
  GET|HEAD   books .................... books.index › routes/web.php:5
  POST       books ................... books.store › routes/web.php:17
  GET|HEAD   books/create ........... books.create › routes/web.php:13
  GET|HEAD   books/{id} ................ books.show › routes/web.php:9

                                                    Showing [5] routes

The columns, from the left: the method, the address, the route name, then the file and line number where the route is written (routes/web.php:5 means line 5).

⚠️ When the route that answers isn't the one you meant

TL;DR: In routes/web.php, Route::get('/address', function () { ... }) pairs a method (the kind of request) and an address with the code that answers it. {id} captures any one segment (a part of the address between two /) as a string. {id?} may be missing as long as the function has a default value, and ->whereNumber('id') limits it to digits. Routes are checked from the top, and the first match wins. Nothing matches: 404; the address exists but for another method: 405. ->name('books.show') gives a route a name, route('books.show', ['id' => 2]) builds the address from that name, and php artisan route:list shows every route. For new data, answer with response()->json([...], 201).

⚡ One line, one route

Write:

Route::get('/books/{id}', function (string $id) {
    return response()->json(['id' => $id]);
})->name('books.show');

Meaning: A route is a rule in routes/web.php. Route::get pairs the GET method (the kind of request that opens a page) and an address with the function that answers it. {id} captures any one segment (a part of the address between two /), and its value is always a string: /books/2 gives '2', not the number 2.

In the exercise, POST /products creates new data, so it must be answered with status 201: write the second number in response()->json([...], 201).

⚡ The first match wins

Guess first: /books/{id} is written above /books/create. You open /books/create. Which route answers?

The route /books/{id} (its name is books.show), with {"id":"create"}. {id} matches any segment, the word create included, so the /books/create route below it is never checked.

Meaning: Laravel checks routes starting from the top line, and the first route that matches is the one that answers. Write the fixed address (with no parameter like {id}) above the one with a parameter, or limit {id} to digits with ->whereNumber('id'). If nothing matches, the answer is 404. If the address exists but for another method, the answer is 405.

⚡ A route's name builds its address

Write:

route('books.show', ['id' => 2]); // http://127.0.0.1:8000/books/2

Meaning: The function route() builds the full address from a route name, here books.show from ->name('books.show'). ['id' => 2] fills in {id}. If that route's address changes later, every route('books.show', ...) uses the new address right away.

What you will learn