Jun*_*ior 1 php laravel laravel-5 laravel-5.4 laravel-5.5
我正在尝试为API编写CRUD.但是,当验证失败时,我想要返回json基于错误的响应,而不是将用户重定向到主页.
我可以使用以下代码执行此操作
public function store(Request $request)
{
try {
$validator = $this->getValidator($request);
if ($validator->fails()) {
return $this->errorResponse($validator->errors()->all());
}
$asset = Asset::create($request->all());
return $this->successResponse(
'Asset was successfully added!',
$this->transform($asset)
);
} catch (Exception $exception) {
return $this->errorResponse('Unexpected error occurred while trying to process your request!');
}
}
/**
* Gets a new validator instance with the defined rules.
*
* @param Illuminate\Http\Request $request
*
* @return Illuminate\Support\Facades\Validator
*/
protected function getValidator(Request $request)
{
$rules = [
'name' => 'required|string|min:1|max:255',
'category_id' => 'required',
'cost' => 'required|numeric|min:-9999999.999|max:9999999.999',
'purchased_at' => 'nullable|string|min:0|max:255',
'notes' => 'nullable|string|min:0|max:1000',
];
return Validator::make($request->all(), $rules);
}
Run Code Online (Sandbox Code Playgroud)
现在,我想将我的一些代码提取到一个form-request以清理我的控制器.我喜欢将我的代码更改为类似下面的代码.
public function store(AssetsFormRequest $request)
{
try {
if ($request->fails()) {
return $this->errorResponse($request->errors()->all());
}
$asset = Asset::create($request->all());
return $this->successResponse(
'Asset was successfully added!',
$this->transform($asset)
);
} catch (Exception $exception) {
return $this->errorResponse('Unexpected error occurred while trying to process your request!');
}
}
Run Code Online (Sandbox Code Playgroud)
你可以告诉它$request->fails()并且 $request->errors()->all()不会起作用.如何检查请求是否失败,以及如何从表单请求中获取错误?
供您参考,以下是我AssetsFormRequest班级的样子
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class AssetsFormRequest 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 [
'name' => 'required|string|min:1|max:255',
'category_id' => 'required',
'cost' => 'required|numeric|min:-9999999.999|max:9999999.999',
'purchased_at' => 'nullable|string|min:0|max:255',
'notes' => 'nullable|string|min:0|max:1000',
];
}
}
Run Code Online (Sandbox Code Playgroud)
在AssetFormRequest类中,您可以将failedValidation方法覆盖 到以下位置 -
public $validator = null;
protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
$this->validator = $validator;
}
Run Code Online (Sandbox Code Playgroud)
然后你的控制器方法,用你的$ validator对象做任何你想做的事情.可能是以下情况 -
if (isset($request->validator) && $request->validator->fails()) {
return response()->json($request->validator->messages(), 400);
}
Run Code Online (Sandbox Code Playgroud)
您也可以看到此链接以获取更多详细信息.希望能帮助到你 :)
| 归档时间: |
|
| 查看次数: |
8474 次 |
| 最近记录: |