In the previous post entitled A Simple Laravel ACL Example we wrote a simple custom access control list (ACL) and learned that the steps we went through also apply to plain PHP apps as well as to any other PHP framework.
Today we are taking a step further by letting our app authorize validation logic in a decoupled way with the help of Laravel’s form requests.
Since authorization stuff needs to be performed by access control rules, we’re now taking full advantage of our ACL while following one of the five SOLID principles of object oriented design: the Open-Closed principle.
The Open-Closed principle states that object-oriented classes should be open for extension but closed for modification, and this is precisely how the
Illuminate\Foundation\Http\FormRequest class has been implemented.
Don’t let the terminology scare you off. If you have a look at the documentation you will notice the
authorize() method is basically saying:
I’m ready to be overridden out-of-the-box.
So, this is how to extend Laravel’s form request validation mechanism to properly authorize form requests with a one-liner.
authorize() method is overridden in the child class and the current user’s role is checked against the incoming route action in the exact same way we did with our custom ACL middleware.
On the other hand, all form requests must now extend
AbstractAuthorizedFormRequest as shown in the following example.
In a nutshell, we’re trying to follow a good practice in terms of object-oriented design. The validation logic is authorized through access control rules (ACL) in one single location, the
authorize() method in