Laravel URL Generation

Laravel URL Generation

Laravel provides several helpers to assist you in generating URLs for your application.

The Basics

URLs For Named Routes

Allow you to generate URLs without being coupled to the actual URL defined on the route.

Echo route('post.show', ['post' => 1]);

// http://example.com/post/1
Echo route('post.show', ['post' => $post]);

URLs For Controller Actions

$url = action('HomeController@index');
Use App\Http\Controllers\HomeController;

$url = action([HomeController::class, 'index']);
$url = action('UserController@profile', ['id' => 1]);

Default Values

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);
    }
}

You may use the URL::defaults method to define a default value for this parameter that will always be applied during the current request.

Laravel URL Generation — Structure map

Clickable & Draggable!

Laravel URL Generation — Related pages: