Home Laravel 9 Implementing Admin and User Authentication in Laravel 11: A Comprehensive Tutorial

Implementing Admin and User Authentication in Laravel 11: A Comprehensive Tutorial

29 min read
0
1
1,186

Laravel, a widely-used PHP framework, keeps getting better. Its latest version, Laravel 11, now offers powerful features for implementing multiple authentication systems. This is especially useful for applications that need different user types, like administrators and regular users.

By allowing for multiple authentication systems, Laravel 11 empowers applications to create customized experiences for various user roles. For example, admins can access advanced management features, while regular users can focus on basic functionalities.

Installing Laravel 11

Create the new project which name is example-app.type by following command to create the Laravel project.

composer create-project laravel/laravel example-app

After Type the Command you have to wait until the project installation get  finish. After Finished it.let’s do the  setup on database.

Change .env File

By Default Database Connection in Laravel 11 as Sqllite you have change it as mysql and database name give as bnm.

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

After that run the migrate command

php artisan migrate

After that run the Project

php artisan serve

Create Migrations

the mulipule Authentication no need to create the user again.when we install laravel user has been created.only thing we have to do here is
you have add the addition column which name is role

how to do the task is 

php artisan make:migration add_role_to_users_table --table=users

if you run the above command the separate file has been created 2024_05_21_041832_add_role_to_users_table.php like this format

here you have add it as following

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->string('role')->default('user'); // Default role is 'user'
    });
}

public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropColumn('role');
    });
}

Run the migration:

php artisan migrate

Controllers

Create controllers for admin and user logins

Login

php artisan make:controller Admin/AdminLoginController
php artisan make:controller User/UserLoginController

Registation

php artisan make:controller Admin/AdminRegistationController
php artisan make:controller User/UserRegistationController

Update AdminLoginController (app/Http/Controllers/Admin/AdminLoginController.php)

<?php

namespace App\Http\Controllers\Admin;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Hash;
use App\Models\User;
class AdminLoginController extends Controller
{
    public function index()
    {
        return view('admin.login');
    }
    public function admincheck(Request $request)
    { 
     $credentials = $request->validate([
     'email' => ['required', 'email'],
     'password' => ['required'],
        ]);
        
        if (Auth::attempt(array_merge($credentials, ['role' => 'admin']))) {
            return redirect()->intended('admin/dashboard');
        }
        else
        {  
            session()->flash('error', 'Invalid Credentials'); 
            return redirect()->route('admin.login');
        }  

    }


    public function logout(Request $request)
    {
        Auth::logout();

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

        return redirect('/admin/login');
    }

}

 

Update UserLoginController (app/Http/Controllers/Admin/UserLoginController.php)

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Hash;
use App\Models\User;

class LoginController extends Controller
{
    public function index()
    {
        return view('user.login');
    }
    public function check(Request $request)
    {
     $credentials = $request->validate([
     'email' => ['required', 'email'],
     'password' => ['required'],
        ]);
        
        if (Auth::attempt(array_merge($credentials, ['role' => 'user']))) {
            return redirect()->intended('user/dashboard');
        }

        return redirect()->back()->withErrors(['email' => 'User credentials are incorrect']);
    }

    public function logout(Request $request)
    {
        Auth::logout();

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

        return redirect('/login');


      
    }
}

Update AdminRegistationController (app/Http/Controllers/Admin/AdminRegistationController.php)

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Hash;
use App\Models\User;
class AdminRegistationController extends Controller
{
    public function create()
    {
        return view('admin.create');
    }
    public function store(Request $request)
    {
       $input = $request->all();
       User::create([
        'name' => $input['name'],
        'email' => $input['email'],
        'password' => Hash::make($input['password']),
        'role' => 'admin'
        
      ]);
       return view('admin.thank');
    }
}

Update UserRegistationController (app/Http/Controllers/Admin/UserRegistationController.php)

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Hash;
use App\Models\User;

class RegisterController extends Controller
{
    public function create()
    {
        return view('user.create');
    }
    public function store(Request $request)
    {
       $input = $request->all();
       User::create([
        'name' => $input['name'],
        'email' => $input['email'],
        'password' => Hash::make($input['password'])
        
      ]);
       return view('user.thank');
    }
}

Middleware

Create middleware to check for roles.

php artisan make:middleware AdminMiddleware
php artisan make:middleware UserMiddleware

Update AdminMiddleware (app/Http/Middleware/AdminMiddleware.php)

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth; // Add this line
use Symfony\Component\HttpFoundation\Response;

class AdminMiddleware
{
   
    public function handle(Request $request, Closure $next): Response
    {
        if (Auth::check() && Auth::user()->role == 'admin') {
            return $next($request);
        }
        return redirect()->route('admin.login'); // Ensure this route exists
    }
}

Update UserMiddleware (app/Http/Middleware/UserMiddleware.php)

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth; // Add this line
use Symfony\Component\HttpFoundation\Response;

class UserMiddleware
{
   
    public function handle(Request $request, Closure $next): Response
    {
        if (Auth::check() && Auth::user()->role == 'user') {
            return $next($request);
        }
        return redirect()->route('login'); // Ensure this route exists
    }
}

 

Inside the Model Folder there is model which name User add as role

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

Register middleware in app/bootstrap/app.php

->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            'admin' => \App\Http\Middleware\AdminMiddleware::class,
            'user' => \App\Http\Middleware\UserMiddleware::class,
            'clear_cookies' => \App\Http\Middleware\ClearCookies::class,
        ]);
    })

Views

Create registration views for admin and user

Fist you to create the layout file inside the views folder

resources/views/layout.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
@yield('content')
</body>
</html>


Admin Registation 

Create resources/views/admin/create.blade.php

@extends('layout')
@section('content')
  
    <div class="card">
        <div class="card-header">Register Form</div>
        <div class="card-body"> 
        
            <form action= "{{ route('admin.register') }}" method="post">
                
             {!! csrf_field() !!}   
            <label>First Name</label>
            <input type="text" name="name" id="name" class ="form-control"> </br>
      
            <label>Email</label>
            <input type="email" name="email" id="email" class ="form-control"> </br>
            <label>Password</label>

            <input type="password" name="password" id="password" class ="form-control"> </br>


            <input type="submit" value="Save" class="btn btn-success"> 

            </form>
        </div>
    </div>
@stop

 

Admin Login

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

@extends('layout')
@section('content')
  
    <div class="container">
    <table width="100%" height="100%" border="0" cellspacing="0" align="center">
        <tr>
            <td align="center" valign="middle">
                <table class="table-bordered" width="350" border="0" cellpadding="3" cellspacing="3" bgcolor="#FFFFFF">
              
                  
                          <tr>
                              <td height="25" colspan="2" align="left" valign="middle" bgcolor="#FF9900" class="style2">
                                  <div align="center">
                                  <strong>Admin Login</strong>
                                  </div>
                              </td>
                          </tr>

                        <tr>

                            <div id="err" style="color: red">
                                @if(session()->has('error'))
                                <div class="alert alert-danger">{{ session('error') }}</div>
                                @endif
                            </div>

                        </tr>
                        <form  action="{{ route('admin.check') }}" method="POST">
                        {!! csrf_field() !!}   

                        <tr>
                            <td width="118" align="left" valign="middle" class="style1">Username</td>
                            <td width="118" align="left" valign="middle" class="style1">
                                <input type="text" class="form-control" size="10px" id="username" placeholder="Username" name="email">
                            </td>

                        </tr>

                        <tr>
                            <td width="118" align="left" valign="middle" class="style1">Password</td>
                            <td width="118" align="left" valign="middle" class="style1">
                                <input type="password" class="form-control" size="10px" id="password" placeholder="password" name="password">
                            </td>

                        </tr>

                        
                        <tr>
                            <td colspan="2" align="right" valign="middle" class="style1">
                                <button type="submit" class="btn btn-primary" >Sign In</button>
                            </td>
                        </tr>
                    </form>
                </table>

            </td>
        </tr>
    </table>
</div>
</body>
</html>

@stop

@push('css')

<style type="text/css">
        body,td,th{
            color: #000000;
           
        }
        body{
            background-color: #F0F0F0;
            
        }
        .style1
        {
            font-family: arial, helvetica, sans-serif;
            font-size: 14px;
            padding: 12px;
            line-height: 25px;
            border-radius: 4px;
            text-decoration: none;
        }

        .style2
        {
            font-family: arial, helvetica, sans-serif;
            font-size: 17px;
            padding: 12px;
            line-height: 25px;
            border-radius: 4px;
            text-decoration: none;

        }

    </style>

@endpush

Admindashboard

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

@extends('layout')


@section('content')
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Admin Dashboard</div>

                    <div class="card-body">
                        You are logged in as an admin!

                    </div>

                    <div class="card-body">
                        
                    <h1>  {{ auth()->user()->name }}<h1>
                    <form action="{{ route('admin.logout') }}" method="POST" id="logout-form">
                        @csrf
                        <button type="submit" class="btn btn-danger">Logout</button>
                    </form>

                    </div>

                </div>
            </div>
        </div>
    </div>
@endsection

Create resources/views/admin/thank.blade.php

@extends('layout')
@section('content')
  
    <div class="card">
        <div class="card-header">Welcome</div>
        <div class="card-body"> 
           <h2> Thanks You !!!!!!! </h2>
        </div>
    </div>
@stop

UserRegistation 

Create resources/views/user/create.blade.php

@extends('layout')
@section('content')
  
    <div class="card">
        <div class="card-header">Register Form</div>
        <div class="card-body"> 
        
            <form action= "{{ route('register') }}" method="post">
             {!! csrf_field() !!}   
            <label>First Name</label>
            <input type="text" name="name" id="name" class ="form-control"> </br>
      
            <label>Email</label>
            <input type="email" name="email" id="email" class ="form-control"> </br>
            <label>Password</label>
            <input type="password" name="password" id="password" class ="form-control"> </br>
            <input type="submit" value="Save" class="btn btn-success"> 
            </form>
        </div>
    </div>
@stop

UserLogin

Create resources/views/user/login.blade.php

@extends('layout')
@section('content')
  
    <div class="container">
    <table width="100%" height="100%" border="0" cellspacing="0" align="center">
        <tr>
            <td align="center" valign="middle">
                <table class="table-bordered" width="350" border="0" cellpadding="3" cellspacing="3" bgcolor="#FFFFFF">
              
                  
                          <tr>
                              <td height="25" colspan="2" align="left" valign="middle" bgcolor="#FF9900" class="style2">
                                  <div align="center">
                                      <strong>User Login</strong>
                                  </div>
                              </td>
                          </tr>

                        <tr>

                            <div id="err" style="color: red">
                                @if(session()->has('error'))
                                <div class="alert alert-danger">{{ session('error') }}</div>
                                @endif
                            </div>

                        </tr>
                        <form  action="{{ route('check') }}" method="POST">
                        {!! csrf_field() !!}   

                        <tr>
                            <td width="118" align="left" valign="middle" class="style1">Username</td>
                            <td width="118" align="left" valign="middle" class="style1">
                                <input type="text" class="form-control" size="10px" id="username" placeholder="Username" name="email">
                            </td>

                        </tr>

                        <tr>
                            <td width="118" align="left" valign="middle" class="style1">Password</td>
                            <td width="118" align="left" valign="middle" class="style1">
                                <input type="password" class="form-control" size="10px" id="password" placeholder="password" name="password">
                            </td>

                        </tr>

                        
                        <tr>
                            <td colspan="2" align="right" valign="middle" class="style1">
                                <button type="submit" class="btn btn-primary" >Sign In</button>
                            </td>
                        </tr>
                    </form>
                </table>

            </td>
        </tr>
    </table>
</div>
</body>
</html>

@stop

@push('css')

<style type="text/css">
        body,td,th{
            color: #000000;
           
        }
        body{
            background-color: #F0F0F0;
            
        }
        .style1
        {
            font-family: arial, helvetica, sans-serif;
            font-size: 14px;
            padding: 12px;
            line-height: 25px;
            border-radius: 4px;
            text-decoration: none;
        }

        .style2
        {
            font-family: arial, helvetica, sans-serif;
            font-size: 17px;
            padding: 12px;
            line-height: 25px;
            border-radius: 4px;
            text-decoration: none;

        }

    </style>
@endpush

UserDashboard

Create resources/views/user/dashboard.blade.php

@extends('layout')


@section('content')
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">User Dashboard</div>

                    <div class="card-body">
                        You are logged in as an User!
                    </div>

                    <div class="card-body">
                        
                    <h1>  {{ auth()->user()->name }}<h1>
                  
                    <form action="{{ route('user.logout') }}" method="POST" id="logout-form">
                        @csrf
                        <button type="submit" class="btn btn-danger">Logout</button>
                    </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

 

Create resources/views/user/thank.blade.php

@extends('layout')
@section('content')

<div class="card">
<div class="card-header">Welcome</div>
<div class="card-body"> 
<h2> Thanks You !!!!!!! </h2>
</div>
</div>
@stop

Implement the Routes

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\User\UserLoginController;
use App\Http\Controllers\User\UserRegistationController;
use App\Http\Controllers\User\UserDashBoardController;
use App\Http\Controllers\Admin\AdminLoginController;
use App\Http\Controllers\Admin\AdminRegistationController;
use App\Http\Controllers\Admin\AdminDashBoardController;


Route::get('/', function () {
    return view('welcome');
});
// User Authentication Routes
Route::get('/login', [UserLoginController::class, 'index'])->name('login')->middleware('clear_cookies');;
Route::post('/check', [UserLoginController::class, 'check'])->name('check');
Route::get('/register', [UserRegistationController::class, 'create'])->name('register');
Route::post('/register', [UserRegistationController::class, 'store'])->name('user.register');
//middleware implementation
Route::middleware(['auth', 'user'])->group(function () {
    
 Route::get('/user/dashboard', [UserDashBoardController::class, 'dashboard'])->name('user.dashboard');
 Route::get('/records', [RecordViewController::class, 'index'])->name('record.index');
 Route::post('/logout', [UserLoginController::class, 'logout'])->name('user.logout')->middleware('clear_cookies');
});
// Admin Authentication Routes
Route::get('/admin/login', [AdminLoginController::class, 'index'])->name('admin.login')->middleware('clear_cookies');;
Route::post('/admin/check', [AdminLoginController::class, 'admincheck'])->name('admin.check');
Route::get('/admin/register', [AdminRegistationController::class, 'create'])->name('admin.register');
Route::post('/admin/register', [AdminRegistationController::class, 'store'])->name('admin.store');
Route::middleware(['auth', 'admin'])->group(function () {
    Route::get('/admin/dashboard', [AdminDashBoardController::class, 'dashboard'])->name('admin.dashboard');
    Route::post('/admin/logout', [AdminLoginController::class, 'logout'])->name('admin.logout')->middleware('clear_cookies');
     
});

Middleware for Session and Cookie Clearing

clear the session and cookies upon logout.

php artisan make:middleware ClearSessionCookies

Update the app/Http/Middleware/ClearSessionCookies.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class ClearSessionCookies
{
   
    public function handle(Request $request, Closure $next): Response
    {
     
       $response = $next($request);
      
       $cookies = ['laravel_session', 'XSRF-TOKEN'];
       foreach ($cookies as $cookie) {
           $response->headers->clearCookie($cookie);
       }
       return $response;
    }
}

 

Register Middleware

'clear_cookies' => \App\Http\Middleware\ClearCookies::class,

Apply Middleware to Routes

Route::post('logout', [LoginController::class, 'logout'])->middleware('clear.session.cookies')->name('logout');

 

i have attached the video link below. which will do this tutorials step by step.

 

 

 

 

 

 

 

Load More Related Articles
Load More By admin
Load More In Laravel 9

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also

Inventory management system using React

In today’s fast-paced business environment, an efficient inventory management system…