Laravel routing is the mechanism that connects incoming HTTP requests to specific application actions. It determines which controller, function or response should be executed when a user visits a URL or sends a request to an application.

Using Laravel’s routing system, developers can define URLs, handle HTTP methods, capture dynamic parameters, generate links, protect routes with middleware and retrieve database records automatically.

This tutorial covers the essential routing features in modern Laravel applications, with examples compatible with Laravel 12 and Laravel 13 unless otherwise stated.

1. Where Are Routes Defined in Laravel?

Laravel stores route definitions inside the routes directory of an application.

File Purpose
routes/web.php Website pages, forms and session-based requests
routes/api.php Stateless API endpoints, when enabled
routes/console.php Closure-based Artisan commands and console scheduling
bootstrap/app.php Route loading and application configuration in modern Laravel applications

Most website development begins in the routes/web.php file.

Web routes use Laravel’s web middleware group, which provides features such as session management and request forgery protection.

To check which Laravel version your application uses, run the following command from the project directory:

php artisan --version

2. Creating Your First Laravel Route

The simplest route connects a URL to a PHP function, also known as a closure.

Open routes/web.php and add:

use Illuminate\Support\Facades\Route;

Route::get('/hello', function () {
    return 'Hello, World!';
});

Start your local development server:

php artisan serve

Visit:

http://127.0.0.1:8000/hello

The browser should display:

Hello, World!

If Artisan reports a different local address or port, use that address instead.

The route consists of three elements:

  • Route::get() — the HTTP method.

  • /hello — the URI that Laravel matches.

  • function () — the application logic executed when the route is matched.

Routes can return plain text, HTML views, JSON responses or redirects.

For example:

Route::get('/about', function () {
    return view('about');
});

This renders the following Blade template, assuming it exists:

resources/views/about.blade.php

For routes that only display a view, Laravel also provides a shorter syntax:

Route::view('/about', 'about');

3. Understanding HTTP Methods in Laravel Routing

Laravel allows routes to respond to different HTTP methods, depending on the purpose of the request.

HTTP method Laravel method Typical purpose
GET Route::get() Retrieve information
POST Route::post() Submit or create information
PUT Route::put() Replace or update a resource
PATCH Route::patch() Partially update a resource
DELETE Route::delete() Delete a resource
OPTIONS Route::options() Discover communication options

Two routes can use the same URI while handling different HTTP methods.

Route::get('/products', function () {
    return 'Display products';
});

Route::post('/products', function () {
    return 'Create a product';
});

These are two different routes because their HTTP methods differ.

The second example illustrates routing only. A real product creation endpoint would also require input validation, authorization and database logic.

Avoid using GET requests to perform actions that modify or delete application data.

4. Working with Laravel Route Parameters

Route parameters allow applications to capture dynamic values from URLs.

Required parameters

Route::get('/products/{id}', function ($id) {
    return 'Product ID: ' . $id;
});

Visiting:

/products/42

Returns:

Product ID: 42

The value 42 is passed to the route as the $id argument.

Optional parameters

A question mark makes a route parameter optional. The corresponding function argument should have a default value.

Route::get('/welcome/{name?}', function ($name = 'Guest') {
    return 'Welcome, ' . $name;
});
URL Response
/welcome Welcome, Guest
/welcome/Alex Welcome, Alex

Restricting route parameters

Laravel allows developers to control which values a route accepts.

Route::get('/products/{id}', function ($id) {
    return 'Product ID: ' . $id;
})->whereNumber('id');

This route accepts /products/42 but does not match /products/abc.

Common parameter constraints include:

Method Accepted format
whereNumber() Numeric characters
whereAlpha() Alphabetic characters
whereAlphaNumeric() Letters and numbers
whereUuid() UUID format
where() Custom regular expression

Route constraints help prevent unwanted route matches, but they do not replace application-level validation or authorization.

5. Using Named Routes

Named routes allow developers to reference routes without hardcoding their URLs throughout an application.

Route::get('/products/{id}', function ($id) {
    return 'Product ID: ' . $id;
})->name('products.show');

You can generate the corresponding URL using Laravel’s route() helper:

route('products.show', ['id' => 42]);

This generates a URL ending in:

/products/42

Named routes are particularly useful inside Blade templates:

<a href="{{ route('products.show', ['id' => 42]) }}">
    View Product
</a>

They can also be used to generate redirects:

return redirect()->route('products.show', ['id' => 42]);

If the product URL changes later, you only need to update the route definition, rather than every link that references it.

Route names should be unique throughout the application.

6. Connecting Routes to Controllers

Closures are convenient for small examples, but larger applications generally benefit from separating routing definitions from application logic using controllers.

Create a controller:

php artisan make:controller ProductController

Laravel creates:

app/Http/Controllers/ProductController.php

Define a controller action:

<?php

namespace App\Http\Controllers;

class ProductController extends Controller
{
    public function show(string $id): string
    {
        return 'Product ID: ' . $id;
    }
}

Replace the earlier /products/{id} closure route with the following controller route in routes/web.php:

use App\Http\Controllers\ProductController;

Route::get('/products/{id}', [ProductController::class, 'show'])
    ->whereNumber('id')
    ->name('products.show');

When a user visits /products/42, Laravel executes the show() method of ProductController.

Modern syntax vs. older Laravel syntax

Older tutorials frequently use controller strings:

Route::get('/products/{id}', 'ProductController@show');

Although this can still work under suitable namespace configuration, modern Laravel applications should prefer explicit controller class references:

Route::get('/products/{id}', [ProductController::class, 'show']);

This avoids relying on implicit controller namespaces.

7. Organizing Routes with Route Groups and Middleware

Route groups allow multiple routes to share configuration, URL prefixes, middleware and naming conventions.

For example:

Route::prefix('account')
    ->name('account.')
    ->middleware('auth')
    ->group(function () {

        Route::get('/dashboard', function () {
            return 'Account Dashboard';
        })->name('dashboard');

        Route::get('/settings', function () {
            return 'Account Settings';
        })->name('settings');

    });

This creates:

URL Route name Middleware
/account/dashboard account.dashboard auth
/account/settings account.settings auth

The auth middleware requires an authenticated user. A working authentication setup is required for the complete login and redirect flow.

Protecting administrator routes

Authentication alone is not enough to secure an administration panel.

A logged-in customer should not automatically receive access to administrator functions.

For example:

Route::prefix('admin')
    ->name('admin.')
    ->middleware(['auth', 'can:access-admin'])
    ->group(function () {

        Route::get('/dashboard', function () {
            return 'Admin Dashboard';
        })->name('dashboard');

    });

The access-admin authorization gate must first be defined in your application to check the user’s actual permissions.

The distinction is straightforward:

  • Authentication: Who is the user?

  • Authorization: Is the user allowed to perform this action?

Both are essential when protecting sensitive routes.

8. Understanding Laravel Route Model Binding

Route model binding allows Laravel to retrieve an Eloquent model automatically using a value from the URL.

Instead of manually retrieving a product:

$product = Product::findOrFail($id);

You can let Laravel resolve the product through the route.

Assuming your application already has a Product model and its database table, replace the previous product details route with:

use App\Models\Product;

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

When a visitor requests /products/42, Laravel looks for the corresponding product record using the model’s route key, which is normally its primary key.

If no matching product exists, Laravel automatically returns a 404 response.

Route model binding with slugs

Database IDs are not always the best choice for readable public URLs.

Laravel also allows model binding using another column:

Route::get('/shop/{product:slug}', function (Product $product) {
    return view('products.show', [
        'product' => $product,
    ]);
})->name('shop.products.show');

This enables URLs such as:

/shop/wireless-headphones

The product must have a corresponding slug column and value, and the Blade template must exist.

For public product URLs, slugs should be unique and stable.

Security consideration: Model binding retrieves records; it does not determine whether the requesting user has permission to access those records. Use authorization policies or gates where necessary, and avoid exposing sensitive model attributes in responses.

9. Using Laravel Resource Routes

Resource routes simplify the creation of conventional CRUD operations: Create, Read, Update and Delete.

Create a resource controller:

php artisan make:controller ProductController --resource

If ProductController already exists from an earlier example, add the required resource methods to it manually or use a differently named controller rather than overwriting existing work.

Register the resource:

use App\Http\Controllers\ProductController;

Route::resource('products', ProductController::class);

Laravel registers the following routes:

HTTP method URI Controller action
GET /products index
GET /products/create create
POST /products store
GET /products/{product} show
GET /products/{product}/edit edit
PUT/PATCH /products/{product} update
DELETE /products/{product} destroy

Resource routing is especially useful for administration panels, product management systems and other database-driven applications.

For API controllers, use:

Route::apiResource('products', ProductController::class);

API resource routes omit the create and edit routes because APIs typically do not serve HTML forms.

When switching to resource routing, remove or reconcile any earlier route definitions that overlap with the generated routes.

10. Laravel Web Routes vs. API Routes

Choosing the correct route file helps keep browser-based application logic separate from API functionality.

Feature Web routes API routes
File routes/web.php routes/api.php
Typical response HTML or redirect JSON
Session support Enabled by default Stateless by default
CSRF protection Included in the web middleware group Not included in the default API group
Default URL prefix None /api
Typical usage Websites and forms Mobile apps and REST APIs

Enabling API routes

If your modern Laravel installation does not contain routes/api.php, you can enable API routing using:

php artisan install:api

This configures API routing and installs Laravel Sanctum.

Review the resulting dependency and configuration changes before using this command in an existing application.

You can then add a route inside routes/api.php:

use Illuminate\Support\Facades\Route;

Route::get('/status', function () {
    return response()->json([
        'status' => 'online',
    ]);
});

The endpoint is accessible at:

http://127.0.0.1:8000/api/status

Expected response:

{
    "status": "online"
}

The /api prefix is applied automatically by the default configuration. Do not add it again to every individual API route.

Authentication is not automatically required for every API endpoint. Private endpoints must have appropriate authentication and authorization applied.

11. CSRF Protection and HTML Form Routing

When submitting data through HTML forms connected to web routes, Laravel provides protection against cross-site request forgery (CSRF).

For POST forms, include the Blade @csrf directive:

<form method="POST" action="/products">
    @csrf

    <input type="text" name="name">

    <button type="submit">Create Product</button>
</form>

HTML forms do not directly support PUT, PATCH or DELETE as form methods.

Laravel solves this through method spoofing:

<form method="POST" action="/products/42">
    @csrf
    @method('PUT')

    <input type="text" name="name">

    <button type="submit">Update Product</button>
</form>

Laravel processes this request as a PUT request, allowing it to match the appropriate route.

Do not disable request forgery protection simply to resolve form submission errors. Check the form token, session configuration and request origin first.

12. How to List and Debug Laravel Routes

When a Laravel route does not work, the first step should be to confirm that Laravel has registered it correctly.

Run:

php artisan route:list

The output displays route information such as HTTP methods, URIs, route names and actions.

For more detailed middleware information:

php artisan route:list -v

To expand middleware groups:

php artisan route:list -vv

To display routes containing a specific URI:

php artisan route:list --path=products

To inspect API routes:

php artisan route:list --path=api

These commands help identify incorrect HTTP methods, unexpected URL prefixes, missing route names and middleware configuration problems.

13. Common Laravel Routing Problems and Solutions

Problem Possible cause Recommended solution
404 Not Found Route is missing or model does not exist Check route:list, parameters and database records
405 Method Not Allowed Incorrect HTTP method Compare the request method with the route definition
419 Page Expired CSRF token or session problem Check @csrf, cookies and session configuration
403 Forbidden Authorization or request protection failure Check permissions, policies and middleware
Route not defined Incorrect or missing route name Verify the name using route:list
Target class does not exist Incorrect controller import or namespace Check the controller class reference
New routes are not working Outdated route cache Run php artisan route:clear
API endpoint returns 404 API routing is not enabled or the prefix is incorrect Check bootstrap/app.php and API route registration

Route order conflicts

A dynamic route can unintentionally match a URL intended for a more specific route.

Consider this arrangement:

Route::get('/products/{id}', function ($id) {
    return 'Product: ' . $id;
});

Route::get('/products/create', function () {
    return 'Create Product';
});

The dynamic route may capture create as the value of {id}.

A better approach is to define the specific route first and constrain the dynamic parameter:

Route::get('/products/create', function () {
    return 'Create Product';
});

Route::get('/products/{id}', function ($id) {
    return 'Product: ' . $id;
})->whereNumber('id');

If the route uses a slug rather than a numeric ID, define reserved paths before the dynamic route and choose appropriate slug constraints.

Routes work locally but not on the production server

If your routes work with php artisan serve but return server-level 404 errors after deployment, check your web server configuration.

Laravel’s web document root should point to the application’s public directory.

laravel-project/
├── app/
├── bootstrap/
├── config/
├── public/          ← Web server document root
│   └── index.php
├── resources/
├── routes/
├── storage/
└── vendor/

Apache or Nginx must also be configured to forward applicable application requests to Laravel’s front controller, public/index.php.

Do not expose the entire Laravel project directory as the public document root. Doing so can create serious security risks.

14. Improving Production Performance with Route Caching

Laravel can cache route definitions to reduce the processing required to register routes in production applications.

Generate the route cache:

php artisan route:cache

When route definitions change, the cached routes must be regenerated.

To clear the route cache:

php artisan route:clear

During production deployments, regenerate the cache after deploying updated route definitions.

During active development, it is generally easier to work without route caching so that changes become available immediately.

Route caching improves route registration efficiency. It does not cache rendered HTML pages, database queries or API responses.

Building a Maintainable Laravel Routing Structure

A well-organized routing structure makes Laravel applications easier to develop, troubleshoot, secure and maintain.

Use named routes for URL generation, controllers for application logic, route groups for shared configuration, middleware for request checks and model binding for database-backed resources.

When routing problems occur, start with php artisan route:list before changing controller code or web server configurations.

For additional routing features, consult the official Laravel routing documentation.

Share.

Hollands Web is a web design and digital solutions agency specializing in WordPress development, web hosting, SEO, and custom digital solutions. Our team shares practical insights, guides, and strategies to help businesses build, improve, and grow their online presence.

Leave A Reply

Turn on JavaScript to leave a comment.


Math Captcha
79 − 70 =


Ready to get started?

Are you ready
Let’s Make Something
Amazing Together

Need help? Contact our experts
Tell us about your project

Groningen, Netherlands.

Kuipenstreek 1,
Oosterwolde 8431 LX

Istanbul, Turkey.

Hırka-i şerif mah.
Fatih 34091

Newsletter

Sign up to our newsletter!

© 2026, Holland’s Web. All Right Reserved.

Exit mobile version