Generating URLs in Laravel: Helpers, Named Routes, Signed URLs, and Default Parameters
This article explains how Laravel's URL helper functions—such as url, route, signedRoute, temporarySignedRoute, action, and URL::defaults—can be used to generate basic URLs, access the current request URL, create named and signed routes, validate signatures, and set default route parameters, with code examples throughout.
Generating URL Overview
Laravel provides several helper functions for generating URLs within an application, primarily used to build URLs in views and API responses or to create redirect responses elsewhere in the app.
Basics
Generating Basic URLs
The url helper can be used for any URL in the application. The generated URL automatically uses the current request's scheme (HTTP or HTTPS) and host:
$post = App\Post::find(1);
echo url("/posts/{$post->id}");
// http://example.com/posts/1Accessing the Current URL
If the url helper is called without a path, it returns an Illuminate\Routing\UrlGenerator instance, allowing you to retrieve information about the current URL:
// Get the current URL without the query string...
echo url()->current();
// Get the current URL including the query string...
echo url()->full();
// Get the full URL for the previous request...
echo url()->previous();All of these methods can also be accessed via the URL facade:
use Illuminate\Support\Facades\URL;
echo URL::current();URL for Named Routes
The route helper generates a URL for a specified named route, decoupling the URL from the route definition. This means changes to the route's path do not require changes to the route calls.
Route::get('/post/{post}', function () {})->name('post.show');Generating the URL for this route:
echo route('post.show', ['post' => 1]);
// http://example.com/post/1You can also pass an Eloquent model; the helper will automatically extract the model's primary key:
echo route('post.show', ['post' => $post]);The route helper works with routes that have multiple parameters:
Route::get('/post/{post}/comment/{comment}', function () {})->name('comment.show');
echo route('comment.show', ['post' => 1, 'comment' => 3]);
// http://example.com/post/1/comment/3Signed URLs
Laravel can create "signed" URLs for named routes. These URLs include a signature hash in the query string, allowing Laravel to verify that the URL has not been altered since creation. Signed URLs are useful for publicly accessible routes that need protection.
use Illuminate\Support\Facades\URL;
return URL::signedRoute('unsubscribe', ['user' => 1]);To generate a temporary signed URL that expires, use temporarySignedRoute :
use Illuminate\Support\Facades\URL;
return URL::temporarySignedRoute(
'unsubscribe',
now()->addMinutes(30),
['user' => 1]
);Validating Signed Route Requests
To verify that an incoming request has a valid signature, call hasValidSignature on the request instance:
use Illuminate\Http\Request;
Route::get('/unsubscribe/{user}', function (Request $request) {
if (! $request->hasValidSignature()) {
abort(401);
}
// ...
})->name('unsubscribe');Alternatively, assign the Illuminate\Routing\Middleware\ValidateSignature middleware to a route. Register it in the HTTP kernel's routeMiddleware array:
/**
* Application's route middleware.
*/
protected $routeMiddleware = [
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
];After registration, attach the middleware to a route. If the request lacks a valid signature, the middleware automatically returns a 403 response:
Route::post('/unsubscribe/{user}', function (Request $request) {
// ...
})->name('unsubscribe')->middleware('signed');URL for Controller Actions
The action helper generates a URL for a given controller action. You only need to provide the controller class name relative to the App\Http\Controllers namespace:
$url = action('HomeController@index');You can also use the callable array syntax:
use App\Http\Controllers\HomeController;
$url = action([HomeController::class, 'index']);If the controller method requires route parameters, pass them as the second argument:
$url = action('UserController@profile', ['id' => 1]);Default Values
For routes that include parameters such as {locale} , you can define a default value so the parameter is always present in the request. Use URL::defaults in middleware to set the default:
Route::get('/{locale}/posts', function () {})->name('post.index'); <?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\URL;
class SetDefaultLocaleForUrls
{
public function handle($request, Closure $next)
{
URL::defaults(['locale' => $request->user()->locale]);
return $next($request);
}
}Once the default locale is set, you no longer need to pass it explicitly when generating URLs with the route helper.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.