Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate array Laravel 5

My ajax script send array like this: This array belong to Input::get('questions')

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

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

)

In html part user can add multiple fields.

Could you help me with 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';
                }
like image 450
Vladimir Djukic Avatar asked Oct 19 '22 13:10

Vladimir Djukic


1 Answers

Simple: validate each question separately using a 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';
like image 112
Paulo Coghi Avatar answered Oct 22 '22 03:10

Paulo Coghi