2
votes

I have laravel 5.2, i want to validate the csv upload, let's say i have an array from uploaded csv like this :

array(
    'code' => '1',
    'name' => 'asd'
)

and my validation like this

rules = [
    'code' => 'required|numeric',
    'name' => 'required'
];

but i used a locale for my laravel project, so when i export to csv, the title will not alway code and name, i could be japanese language or others, so how to create my validation rule?

How to validate each row from index number?

foreach( $uploaded_data as $row ) {
    $rules = [
        0 => 'required|numeric',
        1 => 'required'
    ];
}
1
Show more uploaded CSV array structure - KmasterYC
Perhaps you need an array validator. You should check this solved question: stackoverflow.com/questions/29952448/validate-array-laravel-5 - Antonio Gocaj

1 Answers

3
votes

Using the Laravel 5.2 Collection class you can call combine() to map an array of 'keys' to a second array.

See the documentation for the combine method.

First we get the keys of the $rules, then combine with the data.

$rules = [
    'code' => 'required|numeric',
    'name' => 'required'
];

$data = [
    'foo' => '1',
    'bar' => 'asd'
];

$combined = collect($rules)->keys()->combine($data);
// [
//     "code" => 1,
//     "name" => 'asd'
// ]

Then, just call validate on $combined.