Laravel表单请求验证返回错误



我使用laravel表单请求验证来验证从视图到控制器的请求。我用的是php artisan make:request SpecializedRequest。但是当验证失败时,它不会返回并且给出错误422。我查阅了laravel文档,但我并不真正理解它。如果验证失败,我如何确保它返回到上一页并返回错误消息我的表单请求验证

<?php
namespace ModulesSpecializedHttpRequests;
use IlluminateFoundationHttpFormRequest;
use ModulesSpecializedEntitiesSpecialized;
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中。

我希望这能有所帮助。

最新更新