使用请求服务验证数据时,如何以json格式返回错误,例如:
return response->json(array("errors' => true, 'errors' => $errors));
请求服务:
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use Auth;
class MyRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
protected $action;
public function authorize()
{
if(Auth::check()) {
return true;
}
}
public function validate() {
return parent::validate();
}
public function all()
{
}
public function messages()
{
}
public function rules()
{
}
}
控制器:
public function store(MyRequest $request) {
$mymodel = new MyModel();
$mymodel->title = 'test';
$model->save();
}
答案 0 :(得分:1)
您不必手动执行,它会自动发送错误响应,可以使用如下:
@if ($errors->has())
<div class="alert alert-danger">
@foreach ($errors->all() as $error)
{{ $error }}<br>
@endforeach
</div>
@endif
或强>
@if ($errors->has('name')) <p class="help-block">{{ $errors->first('name') }}</p> @endif
或强>
跳过请求并执行Validator :: make(),最后执行:
return response($validatorObject->messages(), 500);