How to Authorize Laravel Form Requests With an ACL

Image for post
Image for post

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.

app/Http/Requests/AbstractAuthorizedFormRequest.php

The 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.

app/Http/Requests/StoreRestaurant.php

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 AbstractAuthorizedFormRequest.

You May Also Be Interested in…

A Simple Laravel ACL Example by Jordi Bassagañas

Form Request Validation

Written by

Hi there! How are you today? I blog about technology, the Internet, SEO, programming tips, PHP and more. programarivm.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store