Laravel Named Routes & URL Generation
Imagine your invoicing app has a link to an invoice page in the navbar, in the dashboard, in the email you send to clients, and in the Razorpay payment confirmation. That is easily 20 places where you typed /invoices/1001 by hand.
Now your client says, “Can we change the URL to /billing/invoices/1001?” You open the project and start searching through every file for that URL. You will miss one, and somewhere a customer will click a link and land on a 404 page.
Named routes remove this problem. You give each route a short name once, and from then on you ask Laravel to build the URL for you. If the URL ever changes, you edit one line in routes/web.php and every link updates itself.
The Problem with Hardcoded URLs
Here is the route from the previous lesson, and a link that points to it the hardcoded way:
// routes/web.php
Route::get('/invoices/{invoice}', function (string $invoice) {
return "Invoice {$invoice}";
});
// Somewhere else in your code
$link = '/invoices/1001';
This works today. But the link and the route are two separate pieces of text that happen to match. Nothing connects them. The moment one changes, the other silently breaks, and PHP will not warn you.
Hardcoded URLs also cannot handle the full address. An email to a client needs https://billing.example.in/invoices/1001, not just /invoices/1001. Typing the domain by hand into dozens of places is another future bug.
What Is a Named Route?
A named route is a route with a label attached. You add the label with the name() method:
use Illuminate\Support\Facades\Route;
Route::get('/invoices', function () {
return 'All invoices';
})->name('invoices.index');
Route::get('/invoices/{invoice}', function (string $invoice) {
return "Invoice {$invoice}";
})->name('invoices.show');
The URL is still /invoices/{invoice}, and visitors use it exactly as before. The name invoices.show is only for you and Laravel. Your code now refers to the route by its name, and Laravel looks up the real URL when it needs it.
If you are also using the constraints from the previous lesson, chain them in any order:
Route::get('/invoices/{invoice}', function (string $invoice) {
return "Invoice {$invoice}";
})->whereNumber('invoice')->name('invoices.show');
Naming Conventions
Laravel does not force a naming style, but the community follows one pattern: lowercase words separated by dots, with the resource first and the action last.
invoices.index -> list of invoices invoices.show -> one invoice invoices.create -> form for a new invoice clients.invoices.show -> one invoice that belongs to a client payments.razorpay.callback
Stick to this pattern from day one. When you reach the Resource Routes lesson, you will see that Laravel generates names like invoices.index and invoices.show automatically, so your own names will already match the framework. You will also learn in the Route Groups lesson how to add a common prefix to many names at once.
Generating URLs with the route() Helper
The route() helper takes a route name and returns the full URL:
Route::get('/demo', function () {
return route('invoices.index');
});
Visit /demo on a local server and you will see something like:
http://localhost:8000/invoices
Notice that Laravel added the domain and port for you. On your live server it will use your real domain, so the same code works in every environment.
Routes with Parameters
For a route with a parameter, pass the value as the second argument. The cleanest way is an array with the parameter name as the key:
route('invoices.show', ['invoice' => 1001]);
// http://localhost:8000/invoices/1001
For a route with several parameters, give each one by name:
Route::get('/clients/{client}/invoices/{invoice}', function (string $client, string $invoice) {
return "Client {$client}, Invoice {$invoice}";
})->name('clients.invoices.show');
route('clients.invoices.show', ['client' => 7, 'invoice' => 1001]);
// http://localhost:8000/clients/7/invoices/1001
Using names as array keys makes the order irrelevant. You can also pass plain values in order, like route('invoices.show', 1001), but named keys are safer and easier to read.
The constraints you wrote in the previous lesson still apply. If you pass route('invoices.show', ['invoice' => 'abc']) to a route that only accepts digits, the URL is still generated, but visiting it returns a 404. Constraints guard the incoming request, not the URL builder.
Optional Parameters
Optional parameters work the same way. Leave them out and they disappear from the URL:
Route::get('/invoices/status/{status?}', function (string $status = 'all') {
return "Showing {$status} invoices";
})->name('invoices.status');
route('invoices.status');
// http://localhost:8000/invoices/status
route('invoices.status', ['status' => 'paid']);
// http://localhost:8000/invoices/status/paid
Extra Values Become Query Strings
If you pass a key that is not a placeholder in the route, Laravel does not throw an error. It adds that key to the query string instead:
route('invoices.index', ['status' => 'paid', 'page' => 2]);
// http://localhost:8000/invoices?status=paid&page=2
route('invoices.show', ['invoice' => 1001, 'download' => 'pdf']);
// http://localhost:8000/invoices/1001?download=pdf
This is very handy for filters and pagination links, where the path stays the same and only the query values change.
Relative URLs
By default route() returns an absolute URL with the domain. If you only need the path, pass false as the third argument:
route('invoices.show', ['invoice' => 1001], false);
// /invoices/1001
Using Named Routes in Links and Redirects
The most common place you will use route() is inside a link. In a Blade view, which you will study properly in the Blade Templating chapter, it looks like this:
<a href="{{ route('invoices.show', ['invoice' => 1001]) }}">View Invoice</a>
The second common place is a redirect, for example after a payment is saved:
return redirect()->route('invoices.show', ['invoice' => 1001]);
// Shorter helper with the same result
return to_route('invoices.show', ['invoice' => 1001]);
Redirects get their own lesson later in the Requests, Responses & Middleware chapter, so for now just remember that they accept route names too.
Here is a realistic example. Razorpay needs a callback URL that it can call after a payment completes. Name the route once, then build the URL from the name wherever you need it:
Route::post('/payments/razorpay/callback', function () {
return 'Payment received';
})->name('payments.razorpay.callback');
$callbackUrl = route('payments.razorpay.callback');
// https://billing.example.in/payments/razorpay/callback
If you later move the callback to /webhooks/razorpay, only the route definition changes.
When routes point to controllers, which you will build in the Controllers chapter, the name is added in exactly the same way:
Route::get('/invoices', [InvoiceController::class, 'index'])->name('invoices.index');
Other URL Helpers You Should Know
Named routes are the best choice, but Laravel has a few other helpers for URLs that do not have a name.
url('/invoices/1001');
// http://localhost:8000/invoices/1001
url()->current();
// current URL without the query string
url()->full();
// current URL including the query string
url()->previous();
// the page the visitor came from
You can also build a URL with a query string from any path using url()->query():
url()->query('/invoices', ['status' => 'paid']);
// http://localhost:8000/invoices?status=paid
Use url('/path') only for simple static pages. For anything that maps to one of your routes, route() is safer, because it fails loudly when the name does not exist instead of quietly producing a broken link.
Laravel can also create signed URLs, which are links that cannot be edited without breaking them. You will meet these later in the Email Verification lesson.
Checking the Current Route
Named routes have a second use. You can ask Laravel which route is running right now. This is how navigation bars highlight the active menu item.
use Illuminate\Support\Facades\Route;
Route::currentRouteName();
// "invoices.show"
request()->routeIs('invoices.show');
// true or false
request()->routeIs('invoices.*');
// true for invoices.index, invoices.show, invoices.create and so on
The * wildcard is why the dot naming convention pays off. One check covers every invoice page.
Common Mistakes
Mistake 1: Using a Route Name That Does Not Exist
route('invoice.show', ['invoice' => 1001]);
If you misspell the name (invoice instead of invoices), Laravel throws:
Symfony\Component\Routing\Exception\RouteNotFoundException: Route [invoice.show] not defined.
Check the spelling against your routes/web.php. The error is useful, because a broken link with a hardcoded URL would have failed silently.
Mistake 2: Forgetting a Required Parameter
route('invoices.show');
The route needs {invoice}, but you did not supply it:
Illuminate\Routing\Exceptions\UrlGenerationException: Missing required parameter for [Route: invoices.show] [URI: invoices/{invoice}] [Missing parameter: invoice].
The error message tells you the route name and exactly which parameter is missing. Pass it in the array and the error disappears.
Mistake 3: Giving Two Routes the Same Name
Route::get('/invoices', fn () => 'List')->name('invoices.show');
Route::get('/invoices/{invoice}', fn () => 'One')->name('invoices.show');
Names must be unique. During development, the second one quietly replaces the first, and route('invoices.show') gives you the wrong URL. The problem becomes loud when you cache your routes on a production server:
LogicException: Unable to prepare route [invoices/{invoice}] for serialization. Another route has already been assigned name [invoices.show].
You will learn about route caching in the Security & Performance chapter. Fix duplicates early, so deployment day has no surprises.
Mistake 4: Wrong Domain in Emails and Queued Jobs
In a normal browser request, Laravel reads the domain from the request. In an email sent by a background job or a scheduled command, there is no browser request, so Laravel falls back to the APP_URL value in your .env file.
If APP_URL still says http://localhost, your clients will receive invoice emails with localhost links. Always set APP_URL to your real domain on the production server. You will cover the .env file in detail in the Environment Configuration lesson.
Quick Summary
- Hardcoded URLs break when a route changes, and nothing warns you.
- Give a route a name with
->name('invoices.show'). - Use lowercase dot-separated names with the resource first and the action last, like
invoices.index. - Build URLs with
route('name', ['parameter' => value]). The result is absolute unless you passfalseas the third argument. - Extra array keys that are not route parameters become query string values.
- Use
to_route()orredirect()->route()to redirect by name. - Use
url()->current(),url()->full()andurl()->previous()to work with the current request. - Use
request()->routeIs('invoices.*')to check the active route, for example in a navbar. - Route names must be unique, and
APP_URLmust be correct for emails and queued jobs.
What’s Next
You now have routes with parameters, constraints and names. But as your invoice app grows, you will repeat the same prefix, middleware and name pattern over and over, like /admin/invoices, /admin/clients and /admin/reports. In the next lesson, Route Groups, Prefixes & Controller Groups, you will learn how to apply those shared settings to many routes in one place.