235 views
asked in Laravel by
Laravel Tutorial - Laravel 11 Multiple Authentication (User and Admin - Login, Registration) Using Guard

1 Answer

answered by
Laravel Tutorial 5 - Laravel 11 Multiple Authentication (User and Admin - Login, Registration) Using Guard

In this example, we will add two types of users:

1. User

2. Admin

Step 1: Install Laravel 11

In this step, we will install the laravel 11 application using the below command.

composer create-project laravel/laravel MultiAuthGuard_11

cd MultiAuthGuard_11

Open your project in any text editor like vscode, sublime, notepad++ etc.

Step 2: Database Configuration

Now, we will configure a database in the .env file. And Create database in MySQL.

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=multiauthguard_11

DB_USERNAME=root

DB_PASSWORD=admin@123

Step 3: Configure Laravel UI

// Generate basic scaffolding...

php artisan ui bootstrap

// Generate login / registration scaffolding...

php artisan ui bootstrap --auth

Step 4: Now create Controller for User

php artisan make:controller User/UserController

php artisan make:controller Admin/AdminController

Step 5: Create route in web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\User\UserController;

use App\Http\Controllers\Admin\AdminController;

Route::get('/', function () {

    return view('welcome');

});

Auth::routes();

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

Route::prefix('user')->name('user')->group(function(){

    Route::middleware(['guest:web'])->group(function () {

        Route::view('/login','dashboard.user.login')->name('login');

        Route::view('/register','dashboard.user.register')->name('login');

        Route::post('/create',[UserController::class,'create'])->name('create');

        Route::post('/dologin',[UserController::class,'dologin'])->name('dologin');

    });

    Route::middleware(['auth:web'])->group(function () {

        Route::view('/home','dashboard.user.home')->name('home');

        Route::get('/logout',[UserController::class,'logout'])->name('logout');

    });

});

Route::prefix('admin')->name('admin.')->group(function(){

    Route::middleware(['guest:admin'])->group(function () {

        Route::view('/login','dashboard.admin.login')->name('login');

        Route::post('/dologin',[AdminController::class,'dologin'])->name('dologin');

    });

    Route::middleware(['auth:admin'])->group(function () {

        Route::view('/home','dashboard.admin.home')->name('home');

        Route::get('/logout',[AdminController::class,'logout'])->name('logout');

    });

});

Step 6: Now Create blade pages

resources/views/dashboard/user

    home.blade.php

    login.blade.php

    register.blade.php

Step 7: user/register.blade.php

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Registration</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">

            <h2>Registration page</h2>

            <div class="col-md-5">

                @if(Session::has('success'))

                    <div class="alert alert-success">{{ Session::get('success') }}</div>

                @endif

                @if(Session::has('error'))

                    <div class="alert alert-danger">{{ Session::get('error') }}</div>

                @endif

                <form action="{{ route('user.create') }}" method="POST">

                    @csrf

                    <div class="form-group">

                        <label for="name">Name</label>

                        <input type="text" class="form-control" id="name" name="name" placeholder="Enter full name" value="{{ old('name') }}">

                        <sapn class="text-danger">@error('name'){{ $message }}@enderror</sapn>

                      </div>

                    <div class="form-group">

                      <label for="email">Email address</label>

                      <input type="email" class="form-control" id="email" name="email" placeholder="Enter email" value="{{ old('email') }}">

                      <sapn class="text-danger">@error('email'){{ $message }}@enderror</sapn>

                    </div>

                    <div class="form-group">

                      <label for="password">Password</label>

                      <input type="password" class="form-control" id="password" name="password" placeholder="Password">

                      <sapn class="text-danger">@error('password'){{ $message }}@enderror</sapn>

                    </div>

                    <div class="form-group">

                        <label for="confirm_password">Confirm Password</label>

                        <input type="password" class="form-control" id="confirm_password" name="confirm_password" placeholder="Confirm Password">

                        <sapn class="text-danger">@error('confirm_password'){{ $message }}@enderror</sapn>

                    </div>

                    <button type="submit" class="btn btn-primary">Submit</button>

                    Already Registered <a href="{{ route('user.login') }}">Login</a>

                </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 8: Now  Create function in UserController.php

<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

use App\Models\User;

use Hash;

use Auth;

class UserController extends Controller

{

    public function create(Request $request)

    {

        //dd($request);

        $request->validate([

            'name' => 'required',

            'email' => 'required|email|unique:users,email',

            'password' => 'required|min:8|max:15',

            'confirm_password' => 'required|same:password'

        ],[

            'confirm_password.required' => 'The confirm password field is required.',

            'confirm_password.same' => 'The confirm password and password must be same.',

        ]);

        $user = new User();

        $user->name = $request->name;

        $user->email = $request->email;

        $user->password = Hash::make($request->password);

        $data = $user->save();

        if($data) {

            return redirect()->back()->with('success','You have registered successfully.');

        } else {

            return redirect()->back()->with('error','Your registration failed.');

        }

    }

    public function dologin(Request $request)

    {

        $request->validate([

            'email' => 'required|email',

            'password' => 'required|min:8|max:15',

        ]);

        $check = $request->only('email','password');

        if(Auth::guard('web')->attempt($check)) {

            return redirect('user/home')->with('success','Welcome to dashboard.');

        } else {

            return redirect()->back()->with('error','Login failed.');

        }

    }

    public function logout(Request $request)

    {

        Auth::guard('web')->logout();

        return redirect('user/login');

    }

}

# login.blade.php

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Login</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">

            <h2>User Login page</h2>

            <div class="col-md-5">

                @if(Session::has('success'))

                    <div class="alert alert-success">{{ Session::get('success') }}</div>

                @endif

                @if(Session::has('error'))

                    <div class="alert alert-danger">{{ Session::get('error') }}</div>

                @endif

                <form action="{{ url('user/dologin') }}" method="POST">

                    @csrf

                    <div class="form-group">

                      <label for="email">Email address</label>

                      <input type="email" class="form-control" id="email" name="email" placeholder="Enter email" value="{{ old('email') }}">

                      <sapn class="text-danger">@error('email'){{ $message }}@enderror</sapn>

                    </div>

                    <div class="form-group">

                      <label for="password">Password</label>

                      <input type="password" class="form-control" id="password" name="password" placeholder="Password">

                      <sapn class="text-danger">@error('password'){{ $message }}@enderror</sapn>

                    </div>

                    <button type="submit" class="btn btn-primary">Submit</button>

                    New User <a href="{{ url('user/register') }}">Register Now</a>

                </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>

#home.blade.php

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Dashboard | User</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">

            <h2>Dashboard</h2>

            <div class="col-md-5">

                @if(Session::has('success'))

                    <div class="alert alert-success">{{ Session::get('success') }}</div>

                @endif

                <table class="table table-responsive">

                    <thead>

                        <th>Name</th>

                        <th>Email</th>

                        <th>Action</th>

                    </thead>

                    <tbody>

                        <tr>

                            <td>{{ Auth::guard('web')->user()->name }}</td>

                            <td>{{ Auth::guard('web')->user()->email }}</td>

                            <td>

                                {{--  <a href="{{ url('user/logout') }}" > Logout </a>

                                <a href="{{ route('user.logout') }}" onClick="event.preventDefault();document.getElementById('logout-form')" > Logout </a>  --}}

                                <form name="logout-form" action="{{ url('user/logout') }}" method="POST" >

                                    @csrf

                                    <button type="submit" class="btn btn-primary">Logout</button>

                                </form>

                            </td>

                        </tr>

                    </tbody>

                </table>

            </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 9: auth.php

<?php

return [

    /*

    |--------------------------------------------------------------------------

    | Authentication Defaults

    |--------------------------------------------------------------------------

    |

    | This option defines the default authentication "guard" and password

    | reset "broker" for your application. You may change these values

    | as required, but they're a perfect start for most applications.

    |

    */

    'defaults' => [

        'guard' => env('AUTH_GUARD', 'web'),

        'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),

    ],

    'admin' => [

        'guard' => env('AUTH_GUARD', 'web'),

        'passwords' => env('AUTH_PASSWORD_BROKER', 'admins'),

    ],

    /*

    |--------------------------------------------------------------------------

    | Authentication Guards

    |--------------------------------------------------------------------------

    |

    | Next, you may define every authentication guard for your application.

    | Of course, a great default configuration has been defined for you

    | which utilizes session storage plus the Eloquent user provider.

    |

    | All authentication guards have a user provider, which defines how the

    | users are actually retrieved out of your database or other storage

    | system used by the application. Typically, Eloquent is utilized.

    |

    | Supported: "session"

    |

    */

    'guards' => [

        'web' => [

            'driver' => 'session',

            'provider' => 'users',

        ],

        'admin' => [

            'driver' => 'session',

            'provider' => 'admins',

        ],

    ],

    /*

    |--------------------------------------------------------------------------

    | User Providers

    |--------------------------------------------------------------------------

    |

    | All authentication guards have a user provider, which defines how the

    | users are actually retrieved out of your database or other storage

    | system used by the application. Typically, Eloquent is utilized.

    |

    | If you have multiple user tables or models you may configure multiple

    | providers to represent the model / table. These providers may then

    | be assigned to any extra authentication guards you have defined.

    |

    | Supported: "database", "eloquent"

    |

    */

    'providers' => [

        'users' => [

            'driver' => 'eloquent',

            'model' => env('AUTH_MODEL', App\Models\User::class),

        ],

        'admins' => [

            'driver' => 'eloquent',

            'model' => env('AUTH_MODEL', App\Models\Admin::class),

        ],

        // 'users' => [

        //     'driver' => 'database',

        //     'table' => 'users',

        // ],

    ],

    /*

    |--------------------------------------------------------------------------

    | Resetting Passwords

    |--------------------------------------------------------------------------

    |

    | These configuration options specify the behavior of Laravel's password

    | reset functionality, including the table utilized for token storage

    | and the user provider that is invoked to actually retrieve users.

    |

    | The expiry time is the number of minutes that each reset token will be

    | considered valid. This security feature keeps tokens short-lived so

    | they have less time to be guessed. You may change this as needed.

    |

    | The throttle setting is the number of seconds a user must wait before

    | generating more password reset tokens. This prevents the user from

    | quickly generating a very large amount of password reset tokens.

    |

    */

    'passwords' => [

        'users' => [

            'provider' => 'users',

            'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),

            'expire' => 60,

            'throttle' => 60,

        ],

        'admins' => [

            'provider' => 'admins',

            'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),

            'expire' => 60,

            'throttle' => 60,

        ],

    ],

    /*

    |--------------------------------------------------------------------------

    | Password Confirmation Timeout

    |--------------------------------------------------------------------------

    |

    | Here you may define the amount of seconds before a password confirmation

    | window expires and users are asked to re-enter their password via the

    | confirmation screen. By default, the timeout lasts for three hours.

    |

    */

    'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),

];

Subsequently, launch the Laravel application.

php artisan serve

At this point, access your browser and navigate to the provided URL. Verify the assigned role by logging in with the specified email and password.

http://127.0.0.1:8000/login
...