Backend Development 3 min read

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 Tech Community
Laravel Tech Community
Laravel Tech Community
Generating URLs in Laravel: Basic URLs, Current URL, Named Routes, and Parameter Passing

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/1

2. 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/1

Passing 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/3

These URL generation techniques are simple and enable rapid learning of Laravel routing.

BackendroutingPHPLaravelURL Generation
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.