Choose your Redirect Helper Wisely
Imagine using the following Laravel redirect helpers in your controllers: Redirect::to(‘/pathway’) Redirect::route(‘name’) Redirect::action(‘Controller@method’)
Which one of these helpers (to, route or action) would break fewer things if a change occurred somewhere in your application? For instance, what if one day you decided to rename a controller to better describe it’s responsibility, or change a method name in a controller, or even move a route to/from a group. Would you be able to make just a few adjustments and keep humming along or would you be doing Find & Replace for the next twenty minutes in multiple files wondering if you got everything?
Organizing code and files can help tell a better code narrative, so it’s important that we make choices that will allow us to do so with ease, and to also minimize the number of potential errors that could occur when we decide to change something.
Let’s take a closer look at each and see what the pros and cons are; given the scenario that you will very likely change the controller name, change the method name and change which group the route is in.
Redirect::to(‘/path/way’)
Pros:
Easy to read
Cons:
No framework validation if route is defined or not
Moving a route in or out of a group could invalidate pathway. Route::group “prefix” may alter the pathway.
If this method is used in multiple controllers, we have many locations to update.
Redirect::action(‘Controller@method’)
Pros:
Framework will throw exception if the route is not defined - helps catch errors early
We are free to organize routes (groups, prefixes) without worrying about breaking this redirect
Cons:
If the controller or method name changes this will break very easily.
Tells us a lot about the final destination - do we really need to know which controller and method this should redirect to?
If this method is used in multiple controllers, we have many locations to update.
Redirect::route(‘name’)
Pros
Framework will throw exception if the route name is not defined
We are free to organize routes (groups, prefixes) without worrying about breaking this redirect
Not dependent on a controller or method name
Cons
If this method is used in multiple controllers, we have many locations to update.
I would personally recommend using Redirect::route() as it allows for greater flexibility and is tremendously powerful. For a long time, at Aculios, we used Redirect::action() as it was very expressive and nice to read, but the hidden side is that there are more places to fix/update when something changes. The route names change fair less often than a controller or method name.












