larave 表单验证自定义返回格式
1. 通过修改 FormRequest, 创建 BaseRequest
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
class BaseRequest extends FormRequest
{
/**
* 验证失败处理
*
* @param object $validator
* @throws Illuminate\Http\Exceptions\HttpResponseException
*/
public function failedValidation($validator)
{
$error = $validator->errors()->first();
// $allErrors = $validator->errors()->all(); 所有错误
$response = response()->json([
'code' => '1002',
'msg' => $error,
'data' => [],
]);
throw new HttpResponseException($response);
}
}
2. 通过 Validator
use Validator;
$data = $request->all();
$validator = Validator::make($data, [
'uid' => 'required|unique:users,uid',
'pwd' => 'required|min:6|confirmed',
'pwd_confirmation' => 'required',
'pid' => 'exists:users,uid',
]);
if ($validator->fails()) {
return returnNoData('1002', $validator->errors()->first());
}