Handy access management validation rule for Laravel 5

I worked on several Laravel projects and in almost every project there was a need for some sort of access management control system. Most basic example is validation whether some resource belongs to user. For instance, imagine you have site for freelancers where users can manage their projects, timelogs, invoices etc. When user wants to submit new timelog for some project he needs to select that project from dropdown menu and populate rest of the form. When he submits that form to an API we need to properly validate that request. Let’s say that dropdown menu has its name property set to “project_id”.

$rules = [ // other rules 'project_id' => 'required|exists:projects,id', // other rules ];

The problem

Next important step is to validate whether that project belongs to authenticated user. Now, this is where you have a lot of choices. You can use Illuminate\Auth\Access\Gate class and define user Abilities (see more) or you can write your custom checks in controllers. In my case, I wanted something that requires far less code and can be used as a validation rule. That would solve 2 problems at once:

  1. Reusable code that can be applied to almost every resource
  2. Effortless displaying errors regarding non authorized request

Solution


Originally published at www.laravelfeed.com.