Playing
01. Magically invoking Laravel controller methods

Episodes

0%
Your progress
  • Total: 2m
  • Played: 0m
  • Remaining: 2m
Join or sign in to track your progress

Transcript

00:00
Sometimes I create a single controller for a single job. Sometimes that just feels right and I'm going to show you a little trick in this snippet that allows you to not define a method name because sometimes this can get a little bit confusing when you create a controller that just does one
00:19
job you don't necessarily want to create a method with a name because the controller is the job if that makes sense. If it doesn't make sense I will show you now and hopefully this will save you a little bit of time and clean things up for you. So I'm going to go ahead and
00:33
create a really simple controller. So let's make a controller in here and I'm just going to call this me controller. So let's imagine that this is a controller that allows us to grab information via an API about the currently authenticated user. Now when I create out a single controller when I used to create a
00:51
single controller for a single job I would usually create a method called action. So let's just die dump in here works just so we can see this working and let's come over to our well we'll come over to our web routes for now it doesn't really matter. So I define this out and I would go ahead and say get say
01:10
me and I would define the name of the controller me controller and I would of course use the at symbol and then the name of the action and that would of course register that out. If we come over here to me we see it works. So this can get a little bit confusing. Implementing a method like index doesn't really make
01:27
sense. Show doesn't really make sense because I associate this with a model being passed into a controller that we then show information about. For the me controller that might be the case but I just want to get rid of that all together. Now how do we do this? If we give that a refresh you can see of course
01:43
we have an invalid route action here. If we come over to the me controller what we can actually do is use the PHP invoke magic method. This is going to work in exactly the same way. We'll still get all the request data in. We can still bind models if we want to but that's just going to work in exactly the same
01:59
way. How much nicer is that than having to define out a method name that doesn't really make sense. So if you do have controllers like this this is a really simple tip not to have to define a route action and just use that magic invoke method instead.
1 episode 2 mins

Overview

Some controllers have one action. What should you name that action? Turns out you don't even have to.

Alex Garrett-Smith
Alex Garrett-Smith
Hey, I'm the founder of Codecourse!

Episode discussion

No comments, yet. Be the first!