Contact US


Get Your Project Done by our experts
info@fundaofwebit.com

How to make Multiple Login System using auth in Laravel 5.8 (User + Admin) with Middleware

How to make Multiple Login System using auth in Laravel 5.8 (User + Admin) with Middleware


Step 1: Install your Laravel by issuing the Composer with the command called create-project command in your terminal:


composer create-project --prefer-dist laravel/laravel blog "5.8.*"


Step 2: Setup your database (DB) and set the credentials in your environment file (.env) in your installed laravel application.


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database #do not use this symbol Hash (#) in database
DB_USERNAME=your_username #do not use this symbol Hash (#) in username
DB_PASSWORD=your_password #do not use this symbol Hash (#) in password


Step 3: Go to your application and open the folder by following: app/Providers/AppServiceProvider.php, open this file and add the below code, to set the defaultStringLength to skip the Error called: Specified key was too long error.


    use Illuminate\Support\Facades\Schema;

public function boot()
    {
        Schema::defaultStringLength(191);
    }


Step 4: Now, lets set the login and registration system using laravel auth command by below code:


php artisan make:auth


Step 5: All the setup for login and register is successfully done. Now, let's edit user table which is available in following folder: database / migrations / yoursomedate_create_users_table.php and add the type column for it:


    $table->tinyInteger('role_as')->default('0'); //Add in UserTable before timestamps

   Note: the value which you store in role_as column: 0 = default_user, 1 = admin_user  

Step 6: Let's migrate this table in database by following commad:


php artisan migrate

If you have already migrated the table, then directly you can edit your phpmyadmin database and add the type column named as : role_as TINYINT (4) -> AsDefined (0);

Step 7: Now, Let's Create a custom middleware to check is the Logged_In user is admin or not.! The command for generating middleware as following:


    php artisan make:middleware AdminMiddleware

after middleware generated go to your AdminMiddleware as follows: app/Http/Middleware/AdminMiddleware.php and paste the below code:


use Illuminate\Support\Facades\Auth;

    public function handle($requestClosure $next)
    {
        if(Auth::check())
        {
            if(Auth::user()->role_as == 'admin')
            {
                return $next($request);
            }
            else
            {
                return redirect('/home')->with('status','Access Denied! as you are not as admin');
            }
        }
        else
        {
            return redirect('/home')->with('status','Please Login First');
        }
    }


Step 8: Now Register your Middleware just you created named AdminMiddleware with the following path: app/Http/Kernel.php and goto the routeMiddleware and paste the below code:


protected $routeMiddleware = [

        'isAdmin' => \App\Http\Middleware\AdminMiddleware::class, //Add to the end
    ];


Step 9: Set your Redirection when you are logging as user or admin or any other role provided. Goto path - app/Http/Controller/Auth/LoginController.php and paste the below code:


use Illuminate\Support\Facades\Auth;

    // protected $redirectTo = '/home';

    public function redirectTo()
    {
        if(Auth::user()->role_as == '1'//1 = Admin Login
        {
            return 'dashboard';
        }
elseif(Auth::user()->role_as == '0'// Normal or Default User Login
        {
            return '/';
        }
    }

    // Use ANY ONE ===> the above code OR below code
 
//Second method to Redirect with Message ("STATUS") eg: welcome to dashboard
    protected function authenticated()
    {
        if(Auth::user()->role_as == '1'//1 = Admin Login
        {
            return redirect('dashboard')->with('status','Welcome to your dashboard');
        }
        elseif(Auth::user()->role_as == '0'// Normal or Default User Login
        {
            return redirect('/')->with('status','Logged in successfully');
        }
    }


Step 10: Lets Setup the Route for this Process of multiple authentication as give below:


Route::get('/'function () {
     return view('welcome');
});

Auth::routes();

    Route::group(['middleware' => ['auth','isAdmin']], function () {

        Route::get('/dashboard'function () {
            return view('admin.dashboard');
        });

});


Step 11: Finally, Now let's register. Example: Email_id: admin@gmail.com and Password: Pass*****, but we see that when we register, the role_as default sets as '0', so for the first user you can update its role as '1' by this below command,


    $ php artisan tinker

    >>> use App\User;
    >>>User::where('email', 'admin@gmail.com')->update(['role_as' => '1']);

 then you can create your CRUD Application for Assigning the Roles for this Admin, as in next post i have compled.