Generating URLs using Route Aliases and the LaravelCollective/HTML Package

Blade CSS Views

Committed to the LaraBrain by: wjgilmore (@wjgilmore) at October 26, 2015 6:11 pm

Route aliases are useful for easily updating site URLs should the structure change

I'm a big fan of using the LaravelCollective/HTML package for form generation, however it additionally offers a very useful set of capabilities for route generation that I'm growing increasingly fond of using. You can find the list of functions within their documentation.

One function in particular I'm using with increasing frequency is link_to_route(). Consider the following route, defined in the Larabrain routes.php file:

    'as' => '', 
    function () {
      return view('');

The route alias is called Using link_to_route(), I can generate a link pointing to /buy like so:

{!! link_to_route(
'Learn more', 
 'style' => 'color: white; text-decoration: underline;'
) !!}

This produces the following HTML:

<a style="color: white; text-decoration: underline;" 
  Learn more

Some developers new to route aliases might wonder why even go through all of this trouble and not just embed the link directly into the page. The question is certainly valid, however the advantage of aliases becomes apparent when your site structure changes. What if the pointy-haired boss decided the link URI should instead read /purchase? If you used a route alias, all that's required is a quick update to routes.php as opposed to grepping through the site views to find and replace the old purchase URI.