In this episode, we look at a super handy tip for when you have a Laravel controller dedicated to just one thing—like a controller that just fetches details about the current authenticated user. Traditionally, you'd create a method like index
or show
in your controller, even if those names don't really make sense for what your controller is doing.
Instead, I'll show you how to use PHP's magic __invoke()
method inside your controller. This means you don't need to mess around with arbitrary method names in your routes—your controller just "is" the action! This makes your code a bit cleaner and more intuitive, especially when the controller really only has a single job. We'll see how this works both in the controller itself and in your route definitions, and I'll walk you through a quick example so you can see it in action. This trick should help you write neater, easier-to-understand Laravel code!