我将Laravel
的数据发送到JSON
:
[
{"name":"...", "description": "..."},
{"name":"...", "description": "..."}
]
我有一个扩展了FormRequest
的StoreRequest类:
<?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'
];
}
}
在我的控制器中,我有以下代码,但不适用于数组:
public function import(StoreRequest $request) {
$item = MyModel::create($request);
return Response::HTTP_OK;
}
我发现这种解决方案可以处理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'
];
}
如何更新StoreRequest
和/或import()
代码以避免在rules()
中重复行?
答案 0 :(得分:1)
如果您有一系列数据,则需要将*
首先放在
public function rules()
{
return [
'*.name' => 'required|string|min:1|max:255',
'*.description' => 'nullable|string|max:65535',
];
}