Check Laravel 5 Array

My ajax script send the array as follows: This array belongs to Input::get('questions')

  Array ( [0] => Array ( [name] => fields[] [value] => test1 ) [1] => Array ( [name] => fields[] [value] => test2 ) ) 

In the html part, the user can add several fields .

could you help me? I need something like this:

  $inputs = array( 'fields' => Input::get('questions') ); $rules = array( 'fields' => 'required' ); $validator = Validator::make($inputs,$rules); if($validator -> fails()){ print_r($validator -> messages() ->all()); }else{ return 'success'; } 
+5
source share
2 answers

Simple: check each question separately, using for each:

 // First, your 'question' input var is already an array, so just get it $questions = Input::get('questions'); // Define the rules for *each* question $rules = [ 'fields' => 'required' ]; // Iterate and validate each question foreach ($questions as $question) { $validator = Validator::make( $question, $rules ); if ($validator->fails()) return $validator->messages()->all(); } return 'success'; 
+3
source

Laravel Custom Validation for array elements

Open the following file

 /resources/lang/en/validation.php 

Then the custom message adds

 'numericarray' => 'The :attribute must be numeric array value.', 'requiredarray' => 'The :attribute must required all element.', 

So open another file

 /app/Providers/AppServiceProvider.php 

Now replace the boot function code using the following code.

 public function boot() { // it is for integer type array checking. $this->app['validator']->extend('numericarray', function ($attribute, $value, $parameters) { foreach ($value as $v) { if (!is_int($v)) { return false; } } return true; }); // it is for integer type element required. $this->app['validator']->extend('requiredarray', function ($attribute, $value, $parameters) { foreach ($value as $v) { if(empty($v)){ return false; } } return true; }); } 

Now you can use requiredarray for an array element. And also use the numericarray check for the integer type of the array element.

 $this->validate($request, [ 'arrayName1' => 'requiredarray', 'arrayName2' => 'numericarray' ]); 
0
source

All Articles