【发布时间】:2018-06-15 20:29:14
【问题描述】:
我正在尝试为 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);
}
现在,我想将我的一些代码提取到 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!');
}
}
您可能会说$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',
];
}
}
【问题讨论】:
-
朋友们,请做好单元测试,毕竟你在这里测试的不仅仅是规则,validationData和withValidator函数也可能在那里。 here is my answer
标签: php laravel laravel-5 laravel-5.4 laravel-5.5