Page Contents

Url

class Cake\View\Helper\UrlHelper(View $view, array $config = [])

The UrlHelper makes it easy for you to generate URL’s from your other helpers. It also gives you a single place to customize how URLs are generated by overriding the core helper with an application one. See the Aliasing Helpers section for how to do this.

Generating URLs

Cake\View\Helper\UrlHelper::build(mixed $url = null, boolean|array $full = false)

Returns a URL pointing to a combination of controller and action. If $url is empty, it returns the REQUEST\_URI, otherwise it generates the URL for the controller and action combo. If full is true, the full base URL will be prepended to the result:

echo $this->Url->build([
    "controller" => "Posts",
    "action" => "view",
    "bar"
]);

// Output
/posts/view/bar

Here are a few more usage examples:

URL with extension:

echo $this->Url->build([
    "controller" => "Posts",
    "action" => "list",
    "_ext" => "rss"
]);

// Output
/posts/list.rss

URL (starting with ‘/’) with the full base URL prepended:

echo $this->Url->build('/posts', true);

// Output
http://somedomain.com/posts

URL with GET params and fragment anchor:

echo $this->Url->build([
    "controller" => "Posts",
    "action" => "search",
    "?" => ["foo" => "bar"],
    "#" => "first"
]);

// Output
/posts/search?foo=bar#first

The above example uses the ? key which is useful when you want to be explicit about the query string parameters you are using, or if you want a query string parameter that shares a name with one of your route placeholders.

URL for named route:

echo $this->Url->build(['_name' => 'product-page', 'slug' => 'i-m-slug']);

// Assuming route is setup like:
// $router->connect(
//     '/products/:slug',
//     [
//         'controller' => 'Products',
//         'action' => 'view'
//     ],
//     [
//         '_name' => 'product-page'
//     ]
// );
/products/i-m-slug

The 2nd parameter allows you to define options controlling HTML escaping, and whether or not the base path should be added:

$this->Url->build('/posts', [
    'escape' => false,
    'fullBase' => true
]);

New in version 3.3.5: build() accepts an array as the 2nd argument as of 3.3.5

If you are generating URLs for CSS, Javascript or image files there are helper methods for each of these asset types:

// Outputs /img/icon.png
$this->Url->image('icon.png');

// Outputs /js/app.js
$this->Url->script('app.js');

// Outputs /css/app.css
$this->Url->css('app.css');

New in version 3.2.4: The asset helper methods were added in 3.2.4.

For further information check Router::url in the API.