简体   繁体   中英

How to validate array in Laravel with Request?

I send to Laravel this JSON data:

[
  {"name":"...", "description": "..."},
  {"name":"...", "description": "..."}
]

I have a StoreRequest class extends FormRequest :

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name' => 'required|string|min:1|max:255',
            'description' => 'nullable|string|max:65535'
        ];
    }
}

In my controller I have this code, but it doesn't work with array:

    public function import(StoreRequest $request) {
        $item = MyModel::create($request);

        return Response::HTTP_OK;
    }

I found this solution to handle arrays in the Request rules():

    public function rules()
    {
        return [
            'name' => 'required|string|min:1|max:255',
            'name.*' => 'required|string|min:1|max:255',
            'description' => 'nullable|string|max:65535'
            'description.*' => 'nullable|string|max:65535'
        ];
    }

How can I update the StoreRequest and/or the import() code to avoide duplicate lines in rules() ?

As you have an array of data you need to put * first:

public function rules()
{
   return [
       '*.name' => 'required|string|min:1|max:255',
       '*.description' => 'nullable|string|max:65535',
   ];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM