Laravel 5.4 check if user is active or not and respond with message if not

1.1k views Asked by At

I have a custom login controller, and I need to check if user is active or not and if not respond with message like please active your account first.

Here is my controller

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 );
    }

I can just add active => 1 to the if ( Auth::guard( 'supplier' )->attempt( but this will respond with wrong username or password

but I want it to respond with 'Active your account first'

any help appreciated.

2

There are 2 answers

1
Kevin Pimentel On

I am not entirely sure what you are trying to do, but it seems like you are just trying to customize the validation messages. In laravel 5.4 you can customize the error message that the user sees like 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:

You should be able to do something like

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

But a better way to do this would be using Laravels flash messaging. Essentially you would set a key and message like this:

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

Then to display the message in your view you can simply do this:

@if (Session::has('message'))
    <p>{!! session('message') !!}</p>
@endif
5
Nikola Gavric On
...
    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' ) ];
    }
...