Generating URLs in Laravel: Helper Functions, Current URL Retrieval, Named Routes, and Controller URLs
This article explains how to generate URLs in Laravel using the url helper, retrieve the current or full URL, work with request methods, create named route URLs with parameters, and obtain controller URLs via the action function, providing code examples for each case.
Laravel provides several built-in methods for generating and retrieving URLs, which are essential for any web framework.
Helper function url
The url helper can generate any URL; if no domain is supplied, it defaults to the application's domain.
<code>echo url('http://baidu.com'); // http://baidu.com</code>
<code>echo url('/users/get/3'); // http://localhost:8000/users/get/3</code>Getting the current URL
Laravel offers multiple methods to obtain the current request URL:
<code>echo url()->current(); // current URL without query string</code>
<code>echo url()->full(); // full URL including query string</code>
<code>echo url()->previous(); // previous URL</code>Additional request methods include:
$request->path() – returns only the path component.
$request->url() – same as url()->current() , without query string.
$request->fullUrl() – equivalent to url()->full() , includes query string.
Named route URLs
Routes can be assigned a name and later referenced to generate their URLs. Example:
<code>Route::get('/news', function () {})->name('news');</code>Retrieve the URL:
<code>echo route('news');</code>When the route has parameters, pass them as the second argument:
<code>Route::get('/news/page/{page}/page_num/{pageNum}', function () {})->name('news');
echo route('news', ['page' => 1, 'pageNum' => 15]);</code>Controller URLs
Use the action helper to generate URLs to controller actions:
<code>$url = action('IndexController@index');</code>If the controller method requires parameters, provide them as the second argument:
<code>$url = action('IndexController@index', ['id' => 1]);</code>The article was contributed by the certified author “齐天大圣” on php中文网.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
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.