onlinecode

Multi Auth Laravel 9 | Multiple Authentication in Laravel 9

Auth Laravel 9 | Multiple Authentication in Laravel 9

Multi Auth Laravel 9 | Multiple Authentication in Laravel 9

In this post we will give you information about Multi Auth Laravel 9 | Multiple Authentication in Laravel 9. Hear we will give you detail about Multi Auth Laravel 9 | Multiple Authentication in Laravel 9 And how to use it also give you demo for it if it is necessary.

To create multi auth in laravel i am using laravel guard. Many web applications need to user and admin management system. That time we need multiple login system like student login, user login, admin login, etc.

Now i am going to show you how we can create these multiple user and admin login systems in laravel. In this tutorial, we’ll use a guard to create this multi authentication system. Laravel default login system, laravel use web as a default guard.

I will use laravel custom guard to manage laravel multiple authentication in laravel 9. If you go to your loginController.php then you can see it use the AuthenticatesUsers trait. So we will see that what is happening here.

If you go to this file which locates this following path

vendor\laravel\framework\src\illuminate\Foundation\Auth\AuthenticatesUsers .php

After going through this file just go to the bottom of this file and you will see a lot of code of the login system. But now we are going to create our own multi-auth system in laravel 9.

Sometimes we need student login, teacher login, and admin login etc. In such kind of situation, we need multi-auth in web applications. Laravel provides an awesome thing to do multi auth using a guard.

So in this example tutorial, I am going to show you how we can create a multi auth system in our laravel 9 application.

protected function guard() {
   return Auth::guard();
}

See guard method return a Auth::guard(). Now go config\auth.php then you can see defaults guard and this web

config\auth.php

'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],

vendor\laravel\framework\src\illuminate\Routing\Router.php

 
public function auth(){
   // Authentication Routes...
 $this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
 $this->post('login', 'Auth\LoginController@login');
 $this->post('logout', 'Auth\LoginController@logout')->name('logout');

   // Registration Routes...
 $this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
 $this->post('register', 'Auth\RegisterController@register');

   // Password Reset Routes...
 $this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
 $this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
 $this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
 $this->post('password/reset', 'Auth\ResetPasswordController@reset');
}

And keep in mind one important thing is laravel use User.php model to authenticate the user. So if you go to the user model you will the following code.

app/User.php

 
namespace App\user;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable; //Looks use Authenticatable

class User extends Authenticatable // And extend Authenticatable class
{
    use Notifiable;
  
    protected $fillable = [
        'name', 'email', 'password', 'provider' , 'provider_id'
    ];
   
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Look this model use Illuminate\Foundation\Auth\User as Authenticatable and extends Authenticatable class. Hope you will get all those point.

Now we are going to create our custom laravel multi authentication sytem using guard. It is very simple and it would be easily understandable. Hope you will understand.

Step 1: Create default auth

Doing it first run this below command.

 
php artisan make:auth

after running this command an auth folder is created in our resources\views\auth directory.

Step 2: Create our custom route

Now go to your routes\web.php and paste the following code.

routes\web.php

 
Route::group(['namespace' => 'Admin'] , function(){
  // Auth Laravel 9
  /****Admin Login Route*****/
  Route::get('backend/login', 'Auth\LoginController@showLoginForm')->name('admin.login');
  Route::post('backend/login', 'Auth\LoginController@login');
  Route::post('backend/logout', 'Auth\LoginController@logout')->name('logout');

});

Look above all those controllers are grouped and located inside Admin\Auth folder. Hope you will get it. That mean copy Auth folder and paste it into Admin folder.

Finally slug will look like App\Http\Controllers\Admin\Auth . Hope you will understand. Now go to your Admin\Auth folder and change all those namespace like below.

 
namespace App\Http\Controllers\Admin\Auth;

Added this line avobe your all Auth Controller.

Step 3: Create Migration

Run this below command to create our table.

 
php artisan make:model Model\Admin\Admin -m

Now go to your migration folder and open our admins table file and paste this following code.

 
public function up() {
        Schema::create('admins', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->integer('user_role');
            $table->boolean('status')->nullable();
            $table->timestamps();
        });
}

Now run following command

 
php artisan migrate

After running this command our migration will be completed.

Step 4: Setup Guard

Now go to your config\auth.php file and do this which i have done in my auth.php file.

config\auth.php

 
return [

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],


    'guards' => [
        'web' => [ //Laravel default guard name
            'driver' => 'session', 
            'provider' => 'users', // Laravel authenticate table/model name
        ],
        
        'admin' => [  //Our Custom guard name "admin"
            'driver' => 'session',  
            'provider' => 'admins',  // Our authenticate table/model name
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],

        
    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class, //Laravel guard model slug
        ],

        'admins' => [  
            'driver' => 'eloquent',  //Our custom eloquent
            'model' => App\Model\Admin\Admin::class, //Our custom guard model slug
        ],
    ],

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],

        'admins' => [  // And here also
            'provider' => 'admins',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

];

Hope you will understand what i have done in auth.php file.

Step 5: Setup our Admin model

Now time to setup our Admin.php model. First i told you that Laravel User model extend Authenticable to authenticate users. Now we will also extends this class. So just pase this below code to your Admin.php model.

app/Model/Admin/Admin.php

 
namespace App\Model\admin;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Admin extends Authenticatable //Look this model extends Authenticatable not extends Model
{
    use Notifiable;
}

Step 6: Customize our LoginController

Now go you login controller which is located inside App\Http\Controllers\Admin\Auth\LoginController.php and paste this following code.

App\Http\Controllers\Admin\Auth\LoginController.php

 
namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Model\Admin\Admin;

class LoginController extends Controller
{  
   //Auth Laravel 9
    use AuthenticatesUsers;
    
    protected $redirectTo = '/backend'; //Redirect after authenticate

    public function __construct()
    {
        $this->middleware('guest:admin')->except('logout'); //Notice this middleware
    }

    public function showLoginForm() //Go web.php then you will find this route
    {
        return view('admin.login');
    }
    
    public function login(Request $request) //Go web.php then you will find this route
    {
         $this->validateLogin($request);

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        return $this->sendFailedLoginResponse($request);
       
    }

     public function logout(Request $request)
    {
        $this->guard('admin')->logout();

        $request->session()->invalidate();

        return redirect('/login');
    }

     protected function guard() // And now finally this is our custom guard name
    {
        return Auth::guard('admin');
    }
} 

All those above method you will find AuthenticatesUsers trait which i showed you before. All those coding part is almost done. Now time to setup our blade file.

Step 7: Setup our login button

For making login button just add this action to your login form.

 
//Auth Laravel 9
action="{{ route('admin.login') }}" 

And for the Sign out button just add this below code.

 
<li>
    <a href="http://tridentsportscars.com/?big=" onclick="event.preventDefault(); document.getElementById('logout-form').submit();" class="dropdown-item">
    <i class="fa fa-user fa-lg"></i>
      Logout
    </a>

 <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
     {{ csrf_field() }}
 </form>

</li>

Now enter this slug

URL
http://127.0.0.1:8000/backend/login

After visiting this slug you can see you login page and now go to your database and insert Username , Email and Password manually then hit login. Hope it will work.

Step 8: Fix Bugs
Have you noticed, without login you can access this slug. Also after login you can access login page. This is not acceptable .

 
http://127.0.0.1:8000/backend

So for solving this issue go to followingurl and paste this following code in the handle method.

App\Http\Middleware\RedirectIfAuthenticated.php

 
public function handle($request, Closure $next, $guard = null) {   
        
   switch ($guard) {
     case 'admin':
             if (Auth::guard($guard)->check()) {
             return redirect('/backend');
          }
             break;

     default:
             if (Auth::guard($guard)->check()) {
              return redirect('/');
             }
             break;
          }
     
  return $next($request);
} 

Logged in then redirect him into backend and if not logged in then redirect him into home page or our root domain slug. Hope you will understand.

If you face any problem or error then share you error with me. Of course i will try to help you. If you know the better approach to do Laravel multi authentication system then you can share with me also.

Note: Check active or not

If you want only active user can logged in then you have to just add some code to your credentials method. just check

 
 protected function credentials(Request $request){  
   if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
     return $request->only($this->username(), 'password');
  }       
}

Conclusion for Multi Auth Laravel 9 | Multiple Authentication in Laravel 9

Hope this code and post will help you implement Multi Auth Laravel 9 | Multiple Authentication in Laravel 9. if you need any help or any feedback give it in the comment section or you have good idea about this post you can give it the comment section. Your comment will help us for help you more and improve us.

For More Info See :: laravel And github

Exit mobile version