MasterPHP.in
Try Compiler →
Laravel Tutorial

Laravel Route Parameters & Constraints


Imagine you are building an invoicing app for small businesses in India. Every invoice needs its own page: /invoices/1001, /invoices/1002, /invoices/1003, and so on. If you had to write one route for every invoice, your routes/web.php file would never end.

Route parameters solve this. You write one route with a placeholder, and Laravel passes the changing part of the URL into your code. But a placeholder alone accepts anything. A visitor can open /invoices/abc or /invoices/create-hack, and your code will happily try to find an invoice with that “ID”.

That is where constraints come in. In this lesson you will learn how to capture values from the URL, how to make them optional, and how to restrict them so only valid values reach your code.


What Is a Route Parameter?

A route parameter is a placeholder inside a URL, written in curly braces. Laravel captures whatever the visitor types in that position and hands it to your route.

In the Basic Routing lesson you defined fixed URLs like /about. A parameter makes part of the URL dynamic:

/invoices/1001      ->  {invoice} = "1001"
/invoices/1002      ->  {invoice} = "1002"
/invoices/1003      ->  {invoice} = "1003"

As you saw in the Request Lifecycle lesson, the router matches the incoming URL against your route definitions. Parameters are simply the dynamic parts of that match.


Required Parameters

A required parameter must be present in the URL, otherwise the route does not match at all.

// routes/web.php
use Illuminate\Support\Facades\Route;

Route::get('/invoices/{invoice}', function (string $invoice) {
    return "Showing invoice number: " . $invoice;
});

Visit /invoices/1001 and you will see Showing invoice number: 1001. Visit /invoices without the ID and Laravel returns a 404, because this route needs the parameter.

You can use as many parameters as you need:

Route::get('/clients/{client}/invoices/{invoice}', function (string $client, string $invoice) {
    return "Client {$client}, Invoice {$invoice}";
});

Visiting /clients/7/invoices/1001 prints Client 7, Invoice 1001.

Parameters Are Matched by Position, Not Name

This surprises many beginners. Laravel injects parameters into your function in the order they appear in the URL. The variable names do not have to match the placeholder names:

Route::get('/clients/{client}/invoices/{invoice}', function ($a, $b) {
    // $a = client value, $b = invoice value
    return "$a - $b";
});

This works, but it is confusing. Always use the same names as the placeholders, so the code stays readable.

Parameters and Injected Classes

Sometimes you also want Laravel to give you the current request object. In that case, list the injected class first and the route parameters after it:

use Illuminate\Http\Request;

Route::get('/invoices/{invoice}', function (Request $request, string $invoice) {
    return $request->url() . ' -> ' . $invoice;
});

Laravel resolves Request from the service container, and fills the remaining arguments with route parameters. You will study the request object properly in the Request Object lesson later.

Naming Rules for Parameters

Parameter names can contain letters and underscores. Hyphens are not allowed.

Route::get('/orders/{order_id}', function ($order_id) { /* works */ });
Route::get('/orders/{order-id}', function () { /* does not work */ });

Use {order_id} or simply {order}.


Optional Parameters

Add a ? after the parameter name to make it optional. The function argument must then have a default value.

Route::get('/invoices/status/{status?}', function (string $status = 'all') {
    return "Showing {$status} invoices";
});

Now both URLs work:

/invoices/status         ->  Showing all invoices
/invoices/status/paid    ->  Showing paid invoices

An optional parameter should always come last in the URL. If a required parameter appears after an optional one, the route becomes ambiguous.


The Problem: Parameters Accept Anything

Here is a route with no constraint:

Route::get('/invoices/{invoice}', function (string $invoice) {
    // Imagine we search the database here
    return "Invoice: {$invoice}";
});

This route happily accepts all of these:

/invoices/1001
/invoices/abc
/invoices/-5
/invoices/drop-table-users

Only the first one is a valid invoice ID. The others would reach your database query and return nothing, or worse, cause errors. Validating the shape of the value at the routing level stops this early. The request never reaches your logic.


Regular Expression Constraints with where()

The where() method takes the parameter name and a regular expression. The route matches only when the value fits the pattern.

Route::get('/invoices/{invoice}', function (string $invoice) {
    return "Invoice: {$invoice}";
})->where('invoice', '[0-9]+');

Now /invoices/1001 works, and /invoices/abc returns a 404 page. The pattern [0-9]+ means “one or more digits”.

For multiple parameters, pass an array:

Route::get('/clients/{client}/invoices/{invoice}', function (string $client, string $invoice) {
    return "Client {$client}, Invoice {$invoice}";
})->where([
    'client'  => '[0-9]+',
    'invoice' => 'INV-[0-9]{4}',
]);

Here /clients/7/invoices/INV-1001 matches, but /clients/7/invoices/1001 does not.

Real-World Patterns for Indian Apps

Regular expressions become very useful with Indian data formats. A PIN code is exactly six digits and never starts with zero:

Route::get('/delivery/check/{pin}', function (string $pin) {
    return "Checking delivery for PIN code {$pin}";
})->where('pin', '[1-9][0-9]{5}');

A GSTIN is 15 characters long, with a fixed structure of state code, PAN, entity number, the letter Z, and a check character:

Route::get('/gst/verify/{gstin}', function (string $gstin) {
    return "Verifying GSTIN {$gstin}";
})->where('gstin', '[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z][1-9A-Z]Z[0-9A-Z]');

This only checks the shape of the value. It does not check whether the GSTIN actually exists. For that you would call a GST verification service, and you would still validate user input properly, which is covered in the Forms & Validation chapter.


Helper Methods for Common Patterns

Writing regular expressions for every route gets tiring. Laravel provides helper methods for the most common cases:

// Digits only
Route::get('/invoices/{id}', function (string $id) {
    return $id;
})->whereNumber('id');

// Letters only
Route::get('/cities/{city}', function (string $city) {
    return $city;
})->whereAlpha('city');

// Letters and numbers only
Route::get('/coupons/{code}', function (string $code) {
    return $code;
})->whereAlphaNumeric('code');

// UUID format
Route::get('/payments/{payment}', function (string $payment) {
    return $payment;
})->whereUuid('payment');

// ULID format
Route::get('/receipts/{receipt}', function (string $receipt) {
    return $receipt;
})->whereUlid('receipt');

// Only specific values allowed
Route::get('/orders/status/{status}', function (string $status) {
    return "Orders: {$status}";
})->whereIn('status', ['pending', 'paid', 'failed', 'refunded']);

whereIn() is especially handy. If your Razorpay-based store has only four payment statuses, the route accepts only those four and returns a 404 for everything else.

You can also chain helpers when a route has several parameters:

Route::get('/clients/{client}/invoices/{invoice}', function (string $client, string $invoice) {
    return "Client {$client}, Invoice {$invoice}";
})->whereNumber('client')->whereNumber('invoice');


Global Constraints with Route::pattern()

If the same parameter name appears in many routes, repeating ->whereNumber('invoice') everywhere is wasteful. You can define a rule once, and it applies to every route that uses that parameter name.

Do this inside the boot() method of AppServiceProvider:

// app/Providers/AppServiceProvider.php
namespace App\Providers;

use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        //
    }

    public function boot(): void
    {
        Route::pattern('invoice', '[0-9]+');
        Route::pattern('client', '[0-9]+');
    }
}

In a fresh Laravel 13 project, AppServiceProvider is the only provider listed in bootstrap/providers.php, so this is the natural place. Now every route with {invoice} or {client} accepts digits only, and you can remove the individual where calls:

Route::get('/invoices/{invoice}', fn (string $invoice) => "Invoice {$invoice}");
Route::get('/clients/{client}/invoices/{invoice}', fn (string $client, string $invoice) => "$client / $invoice");

A route-level where() still overrides the global pattern when you need an exception.


Allowing Slashes in a Parameter

By default, a parameter can contain any character except the forward slash /. That means /files/reports/2026/gst.pdf will not match /files/{path}, because the value contains slashes.

To allow slashes, use a pattern that matches everything:

Route::get('/files/{path}', function (string $path) {
    return "Requested file: {$path}";
})->where('path', '.*');

Use this carefully. Never use a raw $path value to read files from disk without strict checking, or you open the door to path traversal attacks. You will learn safe file handling in the Filesystem & Storage lesson.


What Happens When a Constraint Fails?

When a value does not match its constraint, Laravel treats the route as if it does not exist. It tries the next route, and if nothing matches, the visitor sees a 404 page. In debug mode the exception message looks like this:

The route invoices/abc could not be found.

This is the right behaviour. A URL like /invoices/abc is not a “bad request”, it is simply a page that does not exist. You will see how to turn parameters directly into database records in the Route Model Binding lesson.


Common Mistakes

Mistake 1: Placing a Dynamic Route Before a Fixed Route

// Wrong order
Route::get('/invoices/{invoice}', function (string $invoice) {
    return "Invoice {$invoice}";
});

Route::get('/invoices/create', function () {
    return 'Create invoice form';
});

Visiting /invoices/create shows Invoice create, because Laravel matches routes top to bottom and {invoice} accepts any text. No error appears, which makes this bug confusing.

There are two fixes. Define fixed routes first, or add a constraint so {invoice} can never match the word “create”:

Route::get('/invoices/create', fn () => 'Create invoice form');

Route::get('/invoices/{invoice}', fn (string $invoice) => "Invoice {$invoice}")
    ->whereNumber('invoice');

Using both is the safest habit.

Mistake 2: Optional Parameter Without a Default Value

Route::get('/orders/{status?}', function (string $status) {
    return $status;
});

Visit /orders and PHP throws:

ArgumentCountError: Too few arguments to function {closure}(), 0 passed and exactly 1 expected

The fix is to give the argument a default value:

Route::get('/orders/{status?}', function (string $status = 'all') {
    return $status;
});

Mistake 3: Adding Anchors to the Regular Expression

// Wrong
->where('invoice', '^[0-9]+$');

Laravel adds the anchors itself when it builds the final pattern. Adding your own causes an error like:

Routing requirement for "invoice" cannot start with a "^".

Write '[0-9]+' and nothing more.

Mistake 4: Assuming the Value Is a Number

Even with whereNumber(), the parameter reaches your code as a string. Do not rely on it being an integer:

Route::get('/invoices/{invoice}', function (string $invoice) {
    $id = (int) $invoice;   // cast it yourself when you need a number
    return $id + 1;
})->whereNumber('invoice');

Mistake 5: Using Hyphens in Parameter Names

{invoice-id} will not work as a parameter name. Use {invoice_id} or {invoice}.


Quick Summary

  • A route parameter is a placeholder in curly braces, like {invoice}, that captures part of the URL.
  • Required parameters must be in the URL. Optional parameters end with ? and need a default value in your function.
  • Parameters are injected by position, not by name. Injected classes like Request come first.
  • Without a constraint, a parameter accepts any text except /.
  • Use where() with a regular expression, without ^ and $ anchors.
  • Use helpers like whereNumber(), whereAlpha(), whereAlphaNumeric(), whereUuid(), whereUlid() and whereIn() for common cases.
  • Use Route::pattern() in AppServiceProvider::boot() for rules that apply across the whole app.
  • A failed constraint produces a 404, as if the route did not exist.
  • Define fixed routes like /invoices/create before dynamic ones, and constrain dynamic ones.


What’s Next

Your routes can now accept and validate dynamic values, but long URLs scattered through your code are hard to maintain. In the next lesson, Named Routes & URL Generation, you will give routes a name and generate URLs from that name, so a change in a URL never breaks your links.

Frequently Asked Questions

A route parameter is part of the URL path, like the 1001 in /invoices/1001, and is defined in your route with curly braces. A query string comes after a question mark, like /invoices?status=paid, and is read from the request object. Route parameters identify a resource, while query strings usually filter or sort. You will learn to read query strings in the Request Object lesson.
Yes, but it is usually a bad idea. If you write /reports/{year?}/{month?}, a URL with one value is ambiguous because Laravel cannot tell whether it is the year or the month. For most cases, use one optional parameter at the end, or use query strings for extra filters.
It returns a 404 Not Found response. The route simply does not match, so Laravel behaves as if the page does not exist. Constraints are meant for the shape of the URL only. Validating form data and showing error messages is a separate topic covered in the Forms & Validation chapter.
No. Laravel passes route parameters to your function in the same order they appear in the URL, regardless of variable names. For readability you should still use matching names. The exception is route model binding, where the name does matter, and you will see that in a later lesson.
Use whereNumber() when you only need digits, because it is shorter and easier to read. Use where() with a regular expression when the format is custom, such as an invoice number like INV-2026-0042 or a GSTIN. Both do the same job underneath.

Share this tutorial