jeudi 24 septembre 2015

Laravel 5 model validation and authorization

I am facing a dilemma on how to implement validation in my laravel project, let me explain the situation.

  1. I am using an angular JS front end user interface and communicating to laravel using restful resource controllers.
  2. I am using form request validation in my controller's store() and update() methods to validate the data via the rules() method and determining the authorization using authorize() method, which ensures both that my data is correct, and only users with correct permission levels can add/edit data. Everything is working well at this point, so long as the data is coming via a form/ajax request made to the api.

Now, here is the problem. Sometimes the insert/edit operation needs to be done programatically, for e.g. whenever a row is created in table A, a row needs to be created in table B, but before doing so, it should also run the same validation rules and check authorization that it would do if table B was created using a form request, but if I just called say TableA::Create([]) the row would be created without any validation.

Sure, I can use Validator::make() inside the model as well but then, a) it makes the model cluttered b) is a repetition of code

So, my objective is to ensure that no matter how Table A's records are going into the database, if its done from the application, the checks will be performed before saving the data, while keeping the validation and authorization rules central. It seems to me that the way to go is to put a hook onto the model's "saving" event and somehow trigger the formrequest validator? But I am not sure.

I saw Jeffrey Way's automatic model validator, but that is for Laravel 4. Is there any elegant way to do this in Laravel 5.x ?

Also, as an add-on question, when I had asked this question elsewhere, a few people said they were "not a fan of model based validation", without explaining why it is not a good idea for them, so I would also like to know what are the drawbacks of model based validation?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire