Mr Fett
Mr Fett

Reputation: 8509

Manual Laravel Validation using array index (not keys)

A newbie here in terms of Laravel validation - I've searched and checked the manual but can't seem to find an answer to this. I'm using Laravel 8.0.

As per the Laravel manual I have created a manual validation to validate my array, it contains data similar to the below:

$row = array('John','Doe','[email protected]','Manager');

Because the array has no keys, I can't work out how to reference the array items using their index when creating the Validator, I've tried this:

$validatedRow = Validator::make($row, ['0' => 'required|max:2', '1' => 'required']);
$validatedRow = Validator::make($row, [0 => 'required|max:2', 1 => 'required']);
$validatedRow = Validator::make($row, [$row[0] => 'required|max:2', $row[0] => 'required']);

But no luck - does anyone have any suggestions?

Upvotes: 0

Views: 678

Answers (1)

S N Sharma
S N Sharma

Reputation: 1526

Use Validator

use Illuminate\Support\Facades\Validator;

Then Update your code

        $row = array('John','Doe','[email protected]','Manager');
        $rule = [
            '0' => 'required|string',
            '1' => 'required',
            '2' => 'required|email',
            '3' => 'required'
        ];

        $validator = Validator::make($row, $rule);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()->all()], 422);
        }else{
            echo 'ok';
        }

Upvotes: 1

Related Questions