Recently, Action Classes became more popular and more developers convinced to use them.
In fact, Laravel Action classes are mini services which we use to separate any action from each others (just as Single Responsibility Principle).
Actions will try to make code cleaner and simpler and when you have a web-app that is becoming bigger and bigger action classes can help you to develop system easier!
There are a couple of packages to use action classes on Laravel but to be honest, we don’t necessarily need them and a well structured implement will do same thing even better!
Imagine we want to create a very simple system that a user can register, login and have a profile. In this case we should develop an action for each system act.
List of possible actions for this scenario:
First of all we will create an action folder in app directory and for each act we will make a separate class:
We will create an action class:
Then related controller:
php artisan make:controller UserRegisterController
store method on
UserRegisterController and for request validation we should create a specified request type so we run this artisan command:
php artisan make:request StoreUserRequest
After that on
UserRegisterController : (
RegisterNewUser is our action class)
And any action class should have a
handle() function to implement related logic like this:
Well, that’s it for our first action.
Let’s do one more to understand it better.
We will create Action , Controller and proper Request:
php artisan make:controller ForgotPasswordController
php artisan make:request UserForgotPasswordRequest
On this controller we have:
So on, action class will be: