The url() helper function is a shortcut to retrieve URLs for defined routes or manipulate the current URL. It returns a Url object, which behaves like a string when rendered (e.g., in templates) but provides powerful methods for inspection and manipulation.
Get the current URL
To get the current relative URL, call the helper without arguments:
url(); // returns current path, e.g., '/current-url'
Retrieve URLs by name
You can generate URLs for specific routes using their assigned names or controller/class patterns.
Single Route by Name:
If a route is named using the as option, pass the name and any required parameters.
SimpleRouter::get('/product-view/{id}', 'ProductsController@show', ['as' => 'product']);
// With path parameters and query strings
url('product', ['id' => 22], ['category' => 'shoes']); // /product-view/22/?category=shoes
// Only query strings
url('product', null, ['category' => 'shoes']); // /product-view/?category=shoes
Controller Routes:
If using SimpleRouter::controller(), you can target specific methods.
SimpleRouter::controller('/images', ImagesController::class, ['as' => 'picture']);
// Using @ syntax
url('picture@getView', null, ['category' => 'shoes']);
// Using method name as second argument
url('picture', 'getView', ['category' => 'shoes']);
// Using only the method name
url('picture', 'view');
Class-based URLs:
You can reference routes directly via their controller class and method.
SimpleRouter::get('/product-view/{id}', 'ProductsController@show', ['as' => 'product']);
url('ProductsController@show', ['id' => 22]);
REST/Resource URLs:
When using SimpleRouter::resource(), standard RESTful names are available.
SimpleRouter::resource('/phones', PhonesController::class);
url('phones'); // /phones/
url('phones.index'); // /phones/
url('phones.create'); // /phones/create/
url('phones.edit'); // /phones/edit/
// Example of generating a named route URL
SimpleRouter::get('/product-view/{id}', 'ProductsController@show', ['as' => 'product']);
url('product', ['id' => 22], ['category' => 'shoes']);