In this episode, we're cleaning up how we generate URLs in our app by creating a handy route helper function! Right now, we reference routes by their hardcoded URLs all over the place—in our navigation, controllers, and redirects. That's not ideal, because if a route ever changes (even if it's rare), we'd have to hunt down all those places and update the URLs manually.
Instead, it's way better to reference our routes by their names. We start off by setting names on our routes in the web routes file. For example, we name the home route "home" and a user details route as "users.show". Now, these names stay the same even if the URLs themselves change down the line.
Next, we build our helper function called route
. This takes the route name and an optional array of arguments (like user IDs) and uses our router to resolve the correct URL path dynamically. We also wire this up as a Twig function so we can use it easily in our templates.
We then update links in our navigation and homepage templates to use this new route
helper instead of hardcoded paths. For routes needing arguments, like user profile pages, we show how to pass those values directly in Twig.
Finally, we test things out by clicking around the app and confirm that the dynamic URLs are working perfectly. All that's left is for you to go and update any remaining links to use the shiny new helper! This is a really good step for maintainability and is best practice moving forward.