In Laravel we are all used to using the default resource controllers which currently consist of these methods.
One controller for handling all the CRUD requests. Now this doesn’t look bad until you start defining those methods and very soon your controller becomes very fat and hard to manage and it becomes much worse if you are validating requests in the same controller instead of using separate FormRequest classes.
So instead of bloating your controllers with everything we can use a different approach where we will handle each request using its very own separate invokable controller.
So let’s say that we are handling the create and store requests for creating a post in our application. Create request will serve a form to create a Post and store request add that Post in our database.
So let’s create two controllers one for handling create request and another one for handling store request. We can create our invokable controllers using the command:-
Notice that I have stored both the controllers inside a PostManager directory. So all the controllers for managing the Posts will be stored in my PostManager directory.
Our controllers will look something like this:-
Now what about this __invoke function. __invoke function is a type of magic method which will be called when you try to call an object as a function. So in simple words this function makes our class to be called as a function. And this is not just a Laravel specific thing it is also available in core PHP. You will understand this more clearly when you reach the end of this article. Let’s have a look at our routes which would look like this:-
You can also write them like them.
Notice that we haven’t specified any method like we used to before in our routes like ‘CreateController@create’. So this is what __invokable will do for us it will automatically get called.
So now we can handle these request in our controllers.
In our CreateController we are just returning a view which contains a form for creating a Post.
And this is how our StoreController will look like In. It is just calling a method createPost which takes in the form data and create the post. As you can see it looks much cleaner than using a single controller for all the requests and easy to manage too. And you might have noticed that we haven’t validated our request. So for validating request you can still use the FormRequest classes or if you don’t like using them then you can also handle them in the same controller like this:-
Now you shouldn’t be adding too much methods in your invokable controllers and keep it as light as possible so if your validation logic gets quite big then I would still advice you to use the FormRequest classes. Anyways give this approach a try in your next project and see if it helps you. I hope that it was helpful to you and Thanks for reading.
Are you looking for PHP Laravel Developers? Hire from us: https://infynno.com/hire-laravel-developers