Laravel 5 Form Requests - Validating Related Data

FormRequests in Laravel 5 is a good approach for validation and authorization. But how to end, if I have to check a query containing data for relationships from one to many. For example, if I have a simple account. In one account there are many services. My form form request contains the following data:

array (size=5) 'date' => string '2014-11-14' (length=10) 'num' => string '175' (length=3) 'client_id' => string '5' (length=1) 'vat' => string '1' (length=1) 'services' => array (size=2) 0 => array (size=3) 'description' => string 'Service 1' (length=36) 'value' => string '10' (length=2) 'items' => string '2' (length=1) 1 => array (size=3) 'description' => string 'Service 2' (length=11) 'value' => string '20' (length=2) 'items' => string '2' (length=1) 

Now in the InvoiceFormRequest class I can check the invoice data, but how to continue working with the services:

 <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Response; class InvoiceFormRequest extends FormRequest { public function rules() { return [ 'date' => 'required', 'num' => 'required', 'client_id' => 'required', 'vat' => 'required' ]; } public function authorize() { return true; } } 

Thanks in advance!


Update : As I read here in Laravel 5.2, you can write something like this:

 'services.*.description' => 'required', 'services.*.value' => 'required:numeric', 'services.*.items' => 'required:integer' 
+5
source share
2 answers

Now in Laravel 5.2 we have an array check:

 'services.*.description' => 'required', 'services.*.value' => 'required:numeric', 'services.*.items' => 'required:integer' 

http://laravel.com/docs/5.2/releases#laravel-5.2

+2
source

You can use the "array" parameter for the "services" parameters in the rules, but of course this will not check any data contained in each element.

http://laravel.com/docs/master/validation#rule-array

So, I would suggest using something like Marwelln, using a special validator, as well as the "array" rule.

Your rules will probably look like this:

 public function rules() { return [ 'date' => 'required', 'num' => 'required', 'client_id' => 'required', 'vat' => 'required', 'services' => 'array|services' ]; } 

and the custom validator might be something like this (you should put this in the ServiceProvider)

 Validator::extend('services', function($attribute, $value, $parameters) { //foreach $value as $service //validate $service['description'], $service['value'], $service['items'] //return true or false depending on the validation of each element }); 

Hope this helps you find the right direction!

+1
source

Source: https://habr.com/ru/post/1206899/


All Articles