Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Routing

A route connects an address and an HTTP method to the code that builds the response. Web page routes live in routes/web.php.

A basic route

use Illuminate\Support\Facades\Route;
 
Route::get('/hello', function () {
    return 'Hello!';
});

Now the site returns the string "Hello!" at /hello.

HTTP methods

Each request method has its own route method. One address can answer different methods differently:

Route::get('/posts', fn () => 'List of posts');
Route::post('/posts', fn () => 'Post created');
Route::put('/posts/{id}', fn (string $id) => "Post $id updated");
Route::delete('/posts/{id}', fn (string $id) => "Post $id deleted");

GET is used for reading pages, the others for changing data.

Parameters

A part of the address in curly braces is passed to the function as an argument:

Route::get('/users/{id}', function (string $id) {
    return "User $id";
});

An optional parameter is marked with a question mark and gets a default value:

Route::get('/posts/{page?}', function (int $page = 1) {
    return "Page $page";
});

Parameter constraints

To make a route match only suitable values, give the parameter a rule:

Route::get('/users/{id}', function (string $id) {
    return "User $id";
})->whereNumber('id');

The address /users/15 matches, while /users/anna returns a 404 error.

Named routes

A name lets you refer to a route without repeating its address:

Route::get('/profile', fn () => 'Profile')->name('profile');
 
$url = route('profile'); // http://localhost:8000/profile

If the address changes, links built from the name keep working.

Groups

A shared part of the address goes into a group:

Route::prefix('admin')->group(function () {
    Route::get('/users', fn () => 'Users'); // /admin/users
    Route::get('/posts', fn () => 'Posts'); // /admin/posts
});

The php artisan route:list command shows every route in the project.

Common mistake

Laravel checks routes from top to bottom and takes the first match. A route with a parameter placed higher also catches a specific address:

// Wrong: /posts/create lands in the first route with id = "create".
Route::get('/posts/{id}', fn (string $id) => "Post $id");
Route::get('/posts/create', fn () => 'New post');

Put specific addresses above routes with parameters.

Thanks for reading!

Donate to the site — we work hard for you.