Debug School

rakesh kumar
rakesh kumar

Posted on • Edited on

URL Generation

  1. Introduction
  2. The Basics
  3. Generating URLs
  4. Accessing The Current URL
  5. URLs For Named Routes
  6. Signed URLs
  7. URLs For Controller Actions
  8. Default Values

Generating URLs
The url helper may be used to generate arbitrary URLs for your application. The generated URL will automatically use the scheme (HTTP or HTTPS) and host from the current request being handled by the application:

$post = App\Models\Post::find(1);

echo url("/posts/{$post->id}");

// http://example.com/posts/1
Enter fullscreen mode Exit fullscreen mode

Accessing The Current URL
If no path is provided to the url helper, an Illuminate\Routing\UrlGenerator instance is returned, allowing you to access information about the current URL:

// Get the current URL without the query string...

echo url()->current();
Enter fullscreen mode Exit fullscreen mode

Without Parameter
Image description

// Get the current URL including the query string...

echo url()->full();
Enter fullscreen mode Exit fullscreen mode

Image description

// Get the full URL for the previous request...

echo url()->previous();
Enter fullscreen mode Exit fullscreen mode

Each of these methods may also be accessed via the URL facade:

use Illuminate\Support\Facades\URL;

echo URL::current();
Enter fullscreen mode Exit fullscreen mode

URLs For Named Routes
The route helper may be used to generate URLs to named routes. Named routes allow you to generate URLs without being coupled to the actual URL defined on the route. Therefore, if the route's URL changes, no changes need to be made to your calls to the route function. For example, imagine your application contains a route defined like the following:

Route::get('/post/{post}', function (Post $post) {
    //
})->name('post.show');
Enter fullscreen mode Exit fullscreen mode

To generate a URL to this route, you may use the route helper like so:

echo route('post.show', ['post' => 1]);
Enter fullscreen mode Exit fullscreen mode
// http://example.com/post/1
Enter fullscreen mode Exit fullscreen mode

Of course, the route helper may also be used to generate URLs for routes with multiple parameters:

Route::get('/post/{post}/comment/{comment}', function (Post $post, Comment $comment) {
    //
})->name('comment.show');

echo route('comment.show', ['post' => 1, 'comment' => 3]);
Enter fullscreen mode Exit fullscreen mode
// http://example.com/post/1/comment/3
Enter fullscreen mode Exit fullscreen mode

Any additional array elements that do not correspond to the route's definition parameters will be added to the URL's query string:

echo route('post.show', ['post' => 1, 'search' => 'rocket']);
Enter fullscreen mode Exit fullscreen mode
// http://example.com/post/1?search=rocket
Enter fullscreen mode Exit fullscreen mode

Top comments (0)