Which Laravel Helper Do You Use for Your URLs?

Published on by

Which Laravel Helper Do You Use for Your URLs? image

Jacob Bennett did a Twitter poll to see what the community uses for referencing URLs in their Laravel applications. With 500 votes, the overwhelming majority (77%) said they use the route() helper:

Curious…when referencing URLs in your @laravelphp views, which do you use?

RTs welcome! Thanks! ❤️

— Jacob Bennett (@JacobBennett) April 3, 2017

This was a complete surprise to me as I typically only use the URL string style, but it did make me go back to the documentation and take a look at all the different styles that could be employed in a project. Let’s take a look at some of the advantages and disadvantages of each style.

Laravel Action Helper

action('UserController@profile', ['id' => 1])
// http://site.dev/user/profile/1

Advantages: The result is tied to your controller and method name, so you do not have to name each route individually.

Disadvantages: It’s subjective, but the biggest issue I have with this style is you have to type a lot of characters for all your links. The second—and larger—disadvantage is if you happen to change your controller or method names you’ll have to hunt down all the uses each time.

Laravel Route Helper

route('user.profile', ['id' => 1])
// http://site.dev/user/profile/1

Advantages: This style is tied to a named route; if you change a controller name or controller method all your links will continue to work.

Disadvantages: You have to name each route.

Laravel URL Helper

url('user/profile', [1])
// http://site.dev/user/profile/1

Advantages: Like the previous two, the URL helper automatically prepends the full domain name that you have set in config/app.php. The advantage to this option over the others is it is simpler. You do not have to define route names or even controllers.

Disadvantages: If you change your routes you will need to update each use of the string manually.

URL Strings

href="/user/profile/{{ $user->id }}"
// href="/user/profile/1"

Advantages: This shares the same benefit as the URL helper. It’s simple, easy to follow, and as close as possible to standard HTML.

Disadvantages: This does not append the site’s domain name. So you need to be sure you know where the app will be running and that it’s never going to be in a subdirectory.

Other URL Solutions

Outside of the common solutions mentioned above, I have sometimes used the model to generate the URLs. For example, imagine you are building a blog, and you want the URL for the post details to be in the “yyyy/mm/slug” format. One trick is to take advantage of the model accessor feature:

public function getUriAttribute($_)
{
return $this->created_at->format('Y/m/').$this->slug.'/';
}

Then, in your Blade file:

<a href="{{ $post->uri }}">{{ $post->title }}</a>

Now, you can easily change the post’s permalink across your whole site.

Conclusion

With all of these different styles, which one is right for your project? I’m afraid there isn’t a best practice, and the answer is going to come down to you, your team, the size of the app, etc. There are so many variables in place that a one-size-fits-all solution is not possible. What I can say, is I’ve been happy using the string style on small to medium size apps with one to two developers.

Once you start moving to a bigger team and a larger app, I’d imagine either the action or route will be a better solution. The important thing is to decide on one and use it across the project, instead of mixing and matching.

Eric L. Barnes photo

Eric is the creator of Laravel News and has been covering Laravel since 2012.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Battle Ready Laravel

The ultimate guide to auditing, testing, fixing and improving your Laravel applications so you can build better apps faster and with more confidence.

Visit Battle Ready Laravel
Curotec logo

Curotec

Hire the top Latin American Laravel talent. Flexible engagements, budget optimized, and quality engineering.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Join the Mastering Laravel community logo

Join the Mastering Laravel community

Connect with experienced developers in a friendly, noise-free environment. Get insights, share ideas, and find support for your coding challenges. Join us today and elevate your Laravel skills!

Join the Mastering Laravel community
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Generate Documentation in Laravel with AI image

Generate Documentation in Laravel with AI

Read article
Customizing Laravel Optimization with --except image

Customizing Laravel Optimization with --except

Read article
Solo Dumps for Laravel image

Solo Dumps for Laravel

Read article
Download Files Easily with Laravel's HTTP sink Method image

Download Files Easily with Laravel's HTTP sink Method

Read article
Aureus ERP image

Aureus ERP

Read article
Precise Collection Filtering with Laravel's whereNotInStrict image

Precise Collection Filtering with Laravel's whereNotInStrict

Read article