新建一个Request抽象类,其他的Request都继承于它
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
abstract class Request extends FormRequest
{
protected function failedValidation(Validator $validator)
{
$errormsg = $validator->errors()->messages();
foreach ($errormsg as $item) {
$msg = current($item);
break;
};
throw (new HttpResponseException(response()->json([
'code' => 1,
'message' => $msg,
], 422)));
}
}
使用示例
namespace App\Http\Requests;
class UserRequest extends Request
{
public function rules()
{
return [
"username" => "required|string",
"password" => "required|string|min:6"
];
}
public function messages()
{
return [
"username.requried" => "请填写用户名",
"username.string" => "用户名必须为字符串",
"password.required" => "请填写密码",
"password.string" => "密码必须为字符串",
"password.min" => "密码不少于6位"
];
}
}
网友评论