Laravel 5.4检查用户是否处于活动状态,如果没有,则回复消息

时间:2018-02-10 17:02:19

标签: php laravel validation authentication laravel-5.4

我有一个自定义登录控制器, 我需要检查用户是否有效,如果没有回复,请先回复您的帐户。

这是我的控制器

public function login( Request $request ) {
        // validate the form data
        $this->validate( $request, [
            'email'    => 'required|email',
            'password' => 'required|min:6',
        ] );
        // attempt to login the supplier in

        if ( Auth::guard( 'supplier' )->attempt(
            [
                'email'    => $request->email,
                'password' => $request->password,
            ], $request->remember ) ) {

            return redirect()->intended( route( 'supplier-dashboard' ) );
        }

        $errors = [ $this->username() => trans( 'auth.failed' ) ];

        if ( $request->expectsJson() ) {
            return response()->json( $errors, 422 );
        }

        return redirect()->back()
                         ->withInput( $request->only( 'email', 'remember' ) )
                         ->withErrors( $errors );
    }

我可以将active => 1添加到if ( Auth::guard( 'supplier' )->attempt(,但这会回复错误的用户名或密码

但我希望它首先回复您的帐户'

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:0)

我不完全确定您要做什么,但似乎您只是尝试自定义验证消息。在laravel 5.4中,您可以自定义用户看到的错误消息here

You may customize the error messages used by the form request by overriding the messages method. This method should return an array of attribute / rule pairs and their corresponding error messages:

您应该可以执行类似

的操作
public function messages()
{
     return [
         'email.required' => 'Active your account first',
         'password.required'  => 'Active your account first',
     ];
}

但更好的方法是使用Laravels flash messaging。基本上你会设置一个密钥和消息,如下所示:

$request->session()->flash('message', 'Active your account first');

然后要在视图中显示消息,您只需执行以下操作:

@if (Session::has('message'))
    <p>{!! session('message') !!}</p>
@endif

答案 1 :(得分:0)

...
    if ( Auth::guard( 'supplier' )->attempt(
        [
            'email'    => $request->email,
            'password' => $request->password,
        ], $request->remember ) ) {
        if(!Auth::user()->active) {
           Auth::logout();
           $errors = ['active' => 'Please activate your account'];
        } else {
           return redirect()->intended( route( 'supplier-dashboard' ) );
        }
    } else {
        $errors = [ $this->username() => trans( 'auth.failed' ) ];
    }
...