Creating Maintainable Links with the Laravel LaravelCollective/HTML Package

Blade Routing

Committed to the LaraBrain by: wjgilmore (@wjgilmore) at October 21, 2015 12:19 pm

Creating dynamic URLs by escaping to and from HTML is annoying. There is a better way.

Laravel offers a number of different solutions for linking and redirecting to your application's various controller actions. You're certainly free to explicitly link to whatever URI is associated with the route; for instance, when linking to the aforementioned about page you could just reference the associated URI in a standard hyperlink, like so:

<a href="/about">About LaraBrain</a>

Frankly, this approach works just fine, and is after all a standard part of the HTML specification. However, manual linking of this sort becomes somewhat inconvenient when you'd like to for instance pass along parameters. For instance, suppose you'd like to create a URI pointing to a particular tip. Done manually, the code might look like this:

<a href="/tips/{{ $tip->slug }}">{{ $tip->title }}</a>

This haphazard mix of HTML and PHP escaping has always annoyed me, although I'm the first to admit I'm still guilty of it (and I'd imagine you'll find at least one instance of it in the LaraBrain code). There is however a much better solution at least when you're taking advantage of the aforementioned LaravelCollective/HTML package. You can use the link_to_route() function, passing along the route alias, hyperlink title, and any parameters. For instance, the following example will result in the creation of the same hyperlink as that shown above, but do so in a much more coherent fashion:

{!! link_to_route(

You can find an example of this very same syntax in the LaraBrain source code view partial _tip_line_item.blade.php.