Generating URLs in Laravel: Basic URLs, Current URL, Named Routes, and Parameter Passing
This article explains how to generate basic URLs, retrieve the current URL, create named route URLs, and pass single or multiple parameters in Laravel, providing clear code examples for each scenario to help developers quickly master URL handling in the framework.
Laravel provides several helper functions for generating URLs, which are useful for building links in templates, API responses, or creating redirect responses.
1. Generate a basic URL
<?php
$post = App\Post::find(1);
// Parameter passing
echo url("/posts/{$post->id}");
// http://example.com/posts/12. Access the current URL
<?php
echo url();
echo url()->full();
echo url()->previous();Alternatively, you can use the URL facade:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\URL;
class HomeController extends Controller {
echo URL::current();
}3. Generate a named route URL
<?php
Route::get('/post/{post}', function () {})->name('post.show');Access the named route:
<?php
echo route('post.show', ['post' => 1]);
// http://example.com/post/1Passing a model instance as a parameter:
<?php
echo route('post.show', ['post' => $post]);4. Generate a URL with multiple parameters
<?php
Route::get('/post/{post}/comment/{comment}', function () {})->name('comment.show');Access the route with both parameters:
<?php
echo route('comment.show', ['post' => 1, 'comment' => 3]);
// http://example.com/post/1/comment/3These URL generation techniques are simple and enable rapid learning of Laravel routing.
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.