In yesterday's tip, I took a rare stance and proclaimed a rule that should always be followed: use named routes instead of string paths.
I got an email reply from a reader which raises a good question: What about using Laravel's action
helper instead of named routes?
If you haven't used them before, here's what it looks like:
// action helper
return redirect()->action([ProfilesController::class, 'index']);
// compared to the named route approach
return redirect()->route('profiles.index');
The reader makes a good point: With the action helper, you can click directly to the controller, but with a named route you have to bounce to the routes file first and then to the controller action.
And since we're dealing with actual classes, static analysis with no special configuration could yell at me if I have a typo in the class name.
One of the limitations I can see is that it doesn't work with view routes or closure based routes. I can assign names to those, but they don't have a controller for me to reference.
I admit, this is a pretty minor thing though. I tend not to use a lot of those kind of routes in my apps, but I do like the consistency of having one way to refer to all routes in the rare cases where I do use them.
Another possible downside, especially in Blade files, is either having to import the controller namespace or fully qualify the class name. Again, not a huge issue, but is worth considering.
All in all, I really appreciated the reader feedback and thought it was worth sharing with everyone.
Honestly, if I joined a project, and it used action helpers consistently, I wouldn't have a problem with it. Just no string paths, please!
Here to help,
Joel
P.S. Don't be shy! You can always reply to these emails with your own opinions. I welcome it. Or join the community and discuss it with a bunch of fellow Laravel devs.