Search code examples
mysqllaravellaravel-authentication

How to check user activeness (from database) before login in Laravel


In my application, there is a 'status' column in the 'users' table. Which indicates the user activeness. Now I want to check the activeness of the user before login to the system and give a message if he is deactivated. How to do this? There are several answers here, but I cannot make this work with the help of those answers.

This is my LoginController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/dashboard';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {

        $this->middleware('guest')->except('logout');


    }




}

Solution

  • You can use authenticated() method.

    <?php
    
    namespace App\Http\Controllers\Auth;
    
    use App\Http\Controllers\Controller;
    use Illuminate\Foundation\Auth\AuthenticatesUsers;
    use Illuminate\Http\Request;
    use Illuminate\Validation\ValidationException;
    
    class LoginController extends Controller
    {
    
        use AuthenticatesUsers;
    
        /**
         * Where to redirect users after login.
         *
         * @var string
         */
        protected $redirectTo = '/dashboard';
    
        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function __construct()
        {
            $this->middleware('guest')->except('logout');
        }
    
        /**
         * The user has been authenticated.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  mixed  $user
         * @return mixed
         */
        protected function authenticated(Request $request, $user)
        {
            // Check status
            if ($user->status == 'inactive') {
                $this->logout($request);
    
                // Send message
                throw ValidationException::withMessages([
                    $this->username() => [__('Your status is inactive')],
                ]);
            }
        }
    }