【发布时间】:2019-05-05 20:17:44
【问题描述】:
我设置了一个 FormRequest 类来验证来自我的前端的输入(以 FormData 对象的形式),但是它对我的字段(标题和正文)表现得很奇怪。
尽管发送了 FormData(我检查了网络选项卡并执行了 $request->all()),但我得到了标题和正文字段是必需的 244 验证错误,
我还注意到,在删除所需规则后,即使我的两个输入都少于 5 个字符,验证也会成功通过(这不应该发生)。知道是什么原因造成的吗?
所以现在如果需要规则,我的输入将通过并添加到数据库中,如果我将其添加回验证失败并弹出字段必填消息。
我的表单请求:
<?php
namespace App\Http\Requests\bulletins;
use Illuminate\Foundation\Http\FormRequest;
class CreateBulletin extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'image' => 'nullable|sometimes|image|mimes:jpeg,bmp,png,jpg,svg|max:2000',
'title' => 'string|min:5|max:250',
'body' => 'string|min:5|max:250',
];
}
}
我的控制器方法:
public function store(CreateBulletin $request)
{
//dd($request->all());
$bulletin = new Bulletin();
$bulletin->title = $request->input('title');
$bulletin->body = $request->input('body');
$bulletin->image = '/img/others/default.jpg';
if($request->hasFile('image')){
$uploadFile = $request->file('image');
$filename = str_random(6).'.'.$uploadFile->extension();
$uploadFile->storeAs('uploads', $filename);
$bulletin->image = '/uploads/'.$filename;
}
$bulletin->save();
return response()->json([
'bulletin' => $bulletin,
]);
}
我发送的数据的形状:
检查在网络选项卡发送的参数:
-----------------------------1607382142848
Content-Disposition: form-data; name="title"
title of bulletin
-----------------------------1607382142848
Content-Disposition: form-data; name="body"
content of bulletin
-----------------------------1607382142848--
或
做完 dd($request->all())
array:3 [
"title" => "title of bulletin"
"body" => "content of bulletin"
"image" => UploadedFile {#971
-test: false
-originalName: "01-uxpin-modal-signup-form.jpg"
-mimeType: "image/jpeg"
-error: 0
#hashName: null
path: "C:\xampp\tmp"
filename: "php7708.tmp"
basename: "php7708.tmp"
pathname: "C:\xampp\tmp\php7708.tmp"
extension: "tmp"
realPath: "C:\xampp\tmp\php7708.tmp"
aTime: 2018-12-04 11:45:56
mTime: 2018-12-04 11:45:56
cTime: 2018-12-04 11:45:56
inode: 0
size: 48989
perms: 0100666
owner: 0
group: 0
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
linkTarget: "C:\xampp\tmp\php7708.tmp"
}
]
所以你可以看到我的数据到达服务器
【问题讨论】:
-
如果您在自定义请求中使用 App\Http\Requests\Request 代替 Illuminate\Foundation\Http\FormRequest 是否显示相同的结果?
-
我按照你所说的做了,得到以下错误:消息:找不到类'App\Http\Requests\bulletins\FormRequest'
标签: javascript php laravel vue.js