The function of generating URLs is a must-have function for any framework. Laravel provides several methods to generate URLs. Let’s take a look below.
Auxiliary function url
The auxiliary function url can generate any URL. If no domain name is given, the domain name of this system will be used by default.
echo url('http://baidu.com'); //http://baidu.com echo url('/users/get/3'); // http://localhost:8000/user/get/3
Get the current URL
There are many ways to get the current url, in addition to getting the address of the previous page. But there are some differences between these methods.
echo url()->current(); echo url()->full(); echo url()->previous();
If the current URL address is http://www.example.com/news/1?a=b&c=d,
current this method can get the current url(), But it cannot get the query string (i.e.?a=b&c=d), while full can get the complete path.
In addition to the above methods, you can also obtain the current URL address through laravel's response.
$request->path() This method can only obtain the path of the current request, but cannot obtain the domain name and query string
$request->url() This method is used the same as url()->current(), but the query string cannot be obtained.
Route naming URL
We often set a name for a route. After setting it, you can Use this name to get the URL address of the route. The demo code is given below: First set a name for a route, the code is as follows:Route::get('/news', function () { })->name('news');
echo route('news');
Route::get('/news/page/{page}/page_num/{pageNum}', function () { })->name('news');
echo route('news', ['page' => 1, 'page_num' => 15]);
The URL of the controller
The URL of the controller Addresses are also often used in projects. The URL of the controller is obtained through the action function. The following is the demo code:$url = action('IndexController@index');
$url = action('IndexController@index', ['id' => 1]);
laravel framework"
The above is the detailed content of Summary of laravel generating and obtaining different types of URL addresses. For more information, please follow other related articles on the PHP Chinese website!