laravel - Laravel 表单请求验证返回错误
问题描述
我正在使用 laravel 表单请求验证来验证从视图到控制器的请求。我正在使用php artisan make:request SpecializedRequest
。但是当验证失败时它不会返回并给出错误 422。我查看了laravel 文档,但我并不真正理解它。我如何确保验证失败它返回到上一页并显示错误消息我的表单请求验证
<?php
namespace Modules\Specialized\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Modules\Specialized\Entities\Specialized;
class SpecializedRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required',
];
}
/**
* Get the error messages for the defined validation rules.
*
* @return array
*/
public function messages()
{
return [
'name.required' => 'Nama Specialized cannot be empty',
];
}
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
}
我的控制器
/**
* Store a newly created resource in storage.
* @param SpecializedRequest $request
* @return Response
*/
public function store(SpecializedRequest $request)
{
$specialized = Specialized::create($request->validated());
return ($specialized) ? back()->withSuccess('Data has been added') : back()->withError('Something wrong') ;
}
我的刀片
<form action="{{ route('specialized.store') }}" method="{{ $method }}" class="form-horizontal">
@csrf
<fieldset class="content-group">
<div class="form-group">
<label for="name" class="control-label col-lg-2">Name</label>
<div class="col-lg-10">
<input type="text" name="name" class="form-control" value="{{ old('name',isset($specialized->name) ? $specialized->name : '') }}">
<span style="color:red;"> {{$errors->first('name')}} </span>
</div>
</div>
</fieldset>
<div class="text-right">
<button type="submit" class="btn btn-primary">Submit <i class="icon-arrow-right14 position-right"></i></button>
</div>
</form>
尝试了同样的结果
public function store(Request $request)
{
$data = $request->validate([
'name' => 'required',
]);
$specialized = Specialized::create($data->validated());
return ($specialized) ? back()->withSuccess('Data has been added') : back()->withError('Something wrong') ;
}
解决方案
你正在使用哪个版本的 laravel?
我认为你不需要:
$specialized = Specialized::create($request->validated());
尝试:
$specialized = Specialized::create($request->all());
return redirect()->back() ;
然后处理刀片中的错误显示,例如:
@if($errors->any()){{ implode('', $errors->all('<div>:message</div>')) }}@endif
另外,我相信您需要:
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
在您的 SpecializedRequest 中。
我希望这有帮助。
推荐阅读
- php - 递归函数调用自身直到它返回一个值
- javascript - React 对象属性分配仅在第一次有效
- json - 如何从 Twitter API 加载状态?TypeError:字符串索引必须是整数
- angular - 为 MatTableDataSource 加入两个数组 - Angular/TS
- javascript - 使用下拉列表切换日期选择器的数量
- python-3.x - Python循环输入参数
- sql-server - 存储过程中的最后一个条目不更新
- liquid - 在 Liquid 中仅显示非整数的小数
- javascript - 了解 JavaScript 中的寻路算法
- java - Corda jar 启动:地址已在使用中:绑定错误