php - 如何使用请求验证 Laravel 中的数组?
问题描述
我发送到Laravel
这个JSON
数据:
[
{"name":"...", "description": "..."},
{"name":"...", "description": "..."}
]
我有一个 StoreRequest 类扩展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'
];
}
}
在我的控制器中,我有这段代码,但它不适用于数组:
public function import(StoreRequest $request) {
$item = MyModel::create($request);
return Response::HTTP_OK;
}
我在请求规则()中找到了处理数组的解决方案:
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()
?
解决方案
由于您有一组数据,因此您需要先放置*
:
public function rules()
{
return [
'*.name' => 'required|string|min:1|max:255',
'*.description' => 'nullable|string|max:65535',
];
}
推荐阅读
- node.js - Heroku 与 Docker - 错误 H14:没有运行 Web 进程
- android - FragmentTransaction.TRANSIT_NONE 未按预期工作
- vue.js - VueJS - 基于 JSON 响应的嵌套手风琴
- reactjs - 如何将反应钩子用作打字稿的通用组件
- azure - 如何在单个 API 调用中获取单个 VM 的多个 VM 指标(百分比 CPU、DIisk 读取操作/秒、内存等 .. 平台指标)详细信息
- android - Android:如何获取设备当前面向的方向,类似于谷歌地图
- arrays - 这条线如何添加带有常量的数组?
- pandas - 在 pandas.read_parquet 中使用 AWS_PROFILE
- python - 当参数基于用户检查的输入时,如何在 python 烧瓶中使用 pd.read_sql 选择查询?
- java - 数据库结构。处理多个产品 ID 的事务表