Thursday, 3 December 2020

Laravel Multi-authentication

php artisan make:migration create_admins_table --create=admins
Put this code in the Admin migration php file

public function up()
    {
        Schema::create('admins', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

run  php artisan migrate

Add a record in admins table using seeder.

 Next: Create a model name Admin and copy paste below line.

php artisan make:model Models/Admins

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Model;

class Admin extends Model
{
    use Notifiable;
        protected $guard = 'admin';
        protected $fillable = ['name''email''password'];

        protected $hidden = [
            'password''remember_token',
        ];
}


Next In the config/auth.php file, set up the custom guards and providers for users and admins.
'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
         'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],
    ],    
'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admin::class,
        ],        
    ],    

Next step is to create Admin controller
php artisan make:controller Admin\AdminController

class Admincontroller extends Controller {
    public function __construct()
    {
      $this->middleware('auth:admin');
    }
    public function index() {
        return View('admin.dashboard');
    }
}  

Next step is to create Admin Login Controller
php artisan make:controller Admin\AdminLoginController

<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth; use Route;

class AdminLoginController extends Controller
{
    public function __construct()
    {
      $this->middleware('guest:admin', ['except' => ['logout']]);
    }
    public function showLoginForm()
    {
        return View('admin.login');
    }
    
    public function login(Request $request)
    {
      // Validate the form data
      $this->validate($request, [
        'email'   => 'required|email',
        'password' => 'required|min:4'
      ]);
      
      // Attempt to log the user in
      if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember))             
      {
        // if successful, then redirect to their intended location
     
        return redirect('admin/dashboard');
      }
      // if unsuccessful, then redirect back to the login with the form data
      return redirect()->back()->withInput($request->only('email', 'remember'));
     }
    
    public function logout()
    {
        Auth::guard('admin')->logout();
        return redirect('/admin/login');
    }
}

Next Step is Create a new view file with the name admin.login.php for admin
Copy past from login form.
Make sure the <form method="POST" action="{{ route('admin.login') }}"> should be look like this.

Next Step is Create a new view file with the name dashboard.blade.php for admin

This is for laravel 7 . Now we will set our routes; routes/web.php.  

Route::prefix('admin')->group(function() {
    Route::get('/','Admin\AdminLoginController@showLoginForm')->name('admin.login');
    Route::get('/login','Admin\AdminLoginController@showLoginForm')->name('admin.login');
    Route::post('/login', 'Admin\AdminLoginController@login')->name('admin.login');
    Route::get('logout/', 'Admin\AdminLoginController@logout')->name('admin.logout');
    Route::get('/dashboard', 'Admin\AdminController@index')->name('admin.dashboard');
}) ;

This is for laravel 8 . Now we will set our routes; routes/web.php.

Route::get('/', function () { return view('welcome'); });
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::prefix('admin')->group(function () {
    Route::get('/',[App\Http\Controllers\Admin\AdminLoginController::class,'showLoginForm'])->name('admin.login');
    Route::get('login',[App\Http\Controllers\Admin\AdminLoginController::class,'showLoginForm'])->name('admin.login');
    Route::post('login',[App\Http\Controllers\Admin\AdminLoginController::class,'login'])->name('admin.login');
    Route::get('dashboard',[App\Http\Controllers\Admin\AdminController::class,'index'])->name('admin.index');
    Route::get('logout/', [App\Http\Controllers\Admin\AdminLoginController::class,'logout'])->name('admin.logout');
 });


Next step is, we have to set up the different login views for the guards. This in the app/Exceptions/Handler.php

use Illuminate\Support\Arr; use Auth;
protected function unauthenticated($request, AuthenticationException $exception)
{
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }
        
        $guard = Arr::get($exception->guards(), 0);
        switch ($guard){
            case 'admin':
                $login = 'admin.login';
                break;
            default:
                $login = 'login';
                break;
        }
        return redirect()->guest(route($login));
 }

Next step is If the login is successful, redirect to the dashboard of the specific guard. This is done in the RedirectIfAuthenticated.php    
public function handle($request, Closure $next, $guard = null)
    {
        switch ($guard) {
            case 'admin':
                if (Auth::guard($guard)->check()) {
                    return redirect()->route('admin.dashboard');
                }
                break;             
            default:
                if (Auth::guard($guard)->check()) {
                    return redirect('/home');
                }
                break;
        }
        return $next($request);
    }

That's it.

No comments:

Post a Comment

Machine Learning - Potato Leaf Disease Prediction

Step 1: import numpy as np import pandas as pd import splitfolders import matplotlib.pyplot as plt import tensorflow as tf from tensorflow i...