Laravel 5:如何在验证器请求中自定义错误功能?

时间:2015-12-16 05:18:25

标签: laravel-5.1

我的自定义验证请求:

<?php

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;

class AccountPostRequest extends Request
{

    public function authorize() {
        return true;
    }

    public function rules() {
        return [
            'username' => 'required|alpha_dash'
        ];
    }

    public function message() {
        return [
            'username.required'   => 'input your email',
            'username.alpha_dash' => 'email format error'
        ];
    }

    protected function formatErrors(Validator $validator) {

        return $validator->errors()->all();
    }


    //here is my question, how to invoke this callback when the validation fails,
    //or has any other function like the "before" or "after" filters
    protected function callback(Validator $validator) {
        if ($validator->fails()) {
            //do some thing
        } else {
            //do some thins
        }
    }


}

?>

我的控制器:

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\AccountPostRequest;

class AccountController extends Controller
{

    public function login(AccountPostRequest $request) {
        //...
    }


}

如您所知,如果请求验证失败,它将不会继续执行AccountController的登录功能。

我的问题是如何在验证失败时调用回调,或者具有任何其他功能,如&#34;之前&#34;或&#34;之后&#34;过滤器?

1 个答案:

答案 0 :(得分:0)

所有经过验证的表单请求都通过Illuminate\Foundation\Http\FormRequest中使用名为Illuminate\Validation\ValidatesWhenResolvedTrait的特征的管道传递。该类包含您可能想要修改和覆盖的所有类。

例如,您只需复制并粘贴failedValidation方法并进行自定义即可。

/**
 * Handle a failed validation attempt.
 *
 * @param  \Illuminate\Contracts\Validation\Validator  $validator
 * @return mixed
 */
protected function failedValidation(Validator $validator)
{
    // Do something awesome...
}