243 views
asked in Laravel by
Multi Authentication with Guards Laravel 10

1 Answer

answered by

We will create two types of user like admin and normal user with the help of laravel 10 and guards.

Step 1. Install laravel 10 app

Install laravel 10 app using composer

composer create-project --prefer-dist laravel/laravel multi-auth-laravel-10

Step 2. Create Database and connect with .env

Create a database multi_auth_laravel_10 and put database details in .env file

//.env file

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=multi_auth_laravel_10
DB_USERNAME=root
DB_PASSWORD=

Step 3. Create Admin model and migration table as well as Controller

Create model and migration files using the bellow artisan command. This will create a model Admin.php and a migration file xxxxxx_create_admins_table.php

php artisan make:model Admin -m

-m argument will create the migration file.

Now we have to modify migration file

xxxxxx_create_admins_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{

    /**
     * Run the migrations.
     */

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

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('admins');
    }
};

Now run the migrate command to create admins table into our multi_auth_laravel_10 database.

php artisan migrate

Once the migrate successfully done we will run another command to create a controller. 

Run the following artisan command for make a controller

php artisan make:controller AdminController

Step 4. Create Middleware

php artisan make:middleware AdminMiddleware

//app\Http\Kernel.php

 protected $middlewareAliases = [
        ..............
        'admin' => \App\Http\Middleware\AdminMiddleware::class,
    ];

//AdminMiddleware.php

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */

    public function handle(Request $request, Closure $next): Response
    {
        if(!Auth::guard('admin')->check()){
            return redirect('admin/login');
        }
        return $next($request);
    }
}

Step 5. Frontend scaffolding

composer require laravel/ui

Run the command below to generate login/register scaffolding:

php artisan ui bootstrap --auth

Now Install npm.

npm install

Step 6. Create requird routes

Now we will create all the necessary routes and make some changes in web.php

//resources/web.php

<?php
use App\Http\Controllers\AdminController;
use App\Http\Controllers\HomeController;
use Illuminate\Support\Facades\Route;

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

Route::get('login',[AdminController::class,'login_form'])->name('login.form');
Route::post('login-post',[AdminController::class,'loginPost'])->name('login.post');
Route::group(['middleware'=>'admin'],function(){
    Route::get('logout',[AdminController::class,'logout'])->name('logout');
    Route::get('dashboard',[AdminController::class,'dashboard'])->name('dashboard');
});

Auth::routes();

Route::get('/home', [HomeController::class, 'index'])->name('home');

Step 7. Modify auth.php file

We will update the auth.php file located at config\auth.php to configure guards for admin sessions and providers for admins. In the guards section, we will assign the session as the driver, and in the providers section, we will set eloquent as the driver and the Admin class as the model.

//config/auth.php

 'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        //new
        'admin' => [
               'driver' => 'session',
               'provider' => 'admins',
        ]
    ],

'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],
        //new
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admin::class,
        ]
    ],

Now we will write code for admin login with validation, logout inside AdminController.ph

Step 8. Modify AdminController.php file

\\ App\Http\Controllers\AdminController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class AdminController extends Controller
{
    //Admin Login Form
    public function login()
    {
        return view('admin.login');
    }

    //Admin login post 
    public function loginPost(Request $request){
        $request->validate([
            'email'=>'required',
            'password'=>'required',
        ]);

        if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password])) {
            return redirect()->route('dashboard');
        }else{
            Session::flash('error-message','Invalid Email or Password');
            return back();
        }
    }

    public function dashboard()
    {
        return view('admin.dashboard');
    }

    //Admin logout Method
    public function logout(){
        Auth::guard('admin')->logout();
        return redirect()->route('login');
    }
}

Step 9. Modify Admin.php file

// App\Models\Admin.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Admin extends Authenticatable
{
    use HasFactory;

    protected $fillable = [
        'name',
        'email',
        'password',
    ];

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

Step 10. Create and add below code in login.blade.php file

//resources/views/admin/login.blade.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Multi Authentication with Guards in Laravel 10</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-3"></div>
            <div class="col-md-6">
                <h2 class="py-5">Admin Login</h2>

                @if ($errors->any())
                    <div class="alert alert-danger">
                        <ul>
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif

                @if(Session::has('error-message'))
                    <p class="alert alert-info">{{ Session::get('error-message') }}</p>
                @endif

                <form action="{{ route('login.post') }}" method="post">
                    @csrf
                    <div class="mb-3">
                        <label class="form-label">Email address</label>
                        <input type="email" class="form-control" name="email" placeholder="Enter Email">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Password</label>
                        <input type="password" class="form-control" name="password" placeholder="Enter Password">
                    </div>
                    <input type="submit" class="btn btn-primary" value="Admin Login">
                </form>
            </div>
        </div>
    </div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js" integrity="sha384-BBtl+eGJRgqQAUMxJ7pMwbEyER4l1g+O15P+16Ep7Q9Q+zqX6gSbd85u4mG4QzX+" crossorigin="anonymous"></script>
</body>
</html>

Step 10. Create and add below code in dashboard.blade.php file

// resources/views/admin/dashboard.blade.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Multi Authentication with Guards in Laravel 10</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
</head>
<body>

    <div class="container">
        <div class="row">
            <div class="col-md-3"></div>
            <div class="col-md-6">
                <h2 class="py-5">Admin Dashboard</h2>
                <h4 class="py-2">Welcome !!</h4>
                <a href="{{ route('logout') }}" class="btn btn-danger">Logout</a>
            </div>
        </div>
    </div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js" integrity="sha384-BBtl+eGJRgqQAUMxJ7pMwbEyER4l1g+O15P+16Ep7Q9Q+zqX6gSbd85u4mG4QzX+" crossorigin="anonymous"></script>
</body>
</html>

 Step 11. Create database seeder in DatabaseSeeder.php file

// database/seeders/DatabaseSeeder.php

<?php

namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void

    {

        ...............

         \App\Models\Admin::create([
             'name' => 'Chirags Tutorial',
             'email' => 'inchirags@gmail.com',
             'username' => 'inchirags',
             'password' => Hash::make('admin@1234'),
         ]);
    }
}

Run the following command to insert the admin.

php artisan db:seed

Step 12. Run the below command and Test the Application

// open first terminal

npm run dev 

// open second terminal then run bellow command

php artisan serve

Copy and paste the url 

http://127.0.0.1:8000
...