Creating a Login Page for Admin and User in Laravel
In this guide, we'll build a Laravel authentication system with separate logins for Admin and Users. We'll cover:
✅ Authentication Setup
✅ Database Migration for Users
✅ Middleware for Role-Based Access
✅ Creating Login Views
✅ Redirecting Admin & Users After Login
Step 1: Install Laravel & Authentication
If you haven't already, install Laravel and set up authentication.
1️⃣ Install Laravel
2️⃣ Set Up Database Connection
Edit the .env
file with your database details:
3️⃣ Install Laravel Breeze (Authentication Scaffold)
This will create Login & Registration pages for users.
Step 2: Modify Users Table for Roles
By default, Laravel creates a users table. We need to add a role
column.
1️⃣ Create a Migration
2️⃣ Update Migration File (database/migrations/YYYY_MM_DD_add_role_to_users_table.php
)
3️⃣ Run Migration
Step 3: Modify User Model
Edit app/Models/User.php
to include role
in the fillable
array.
Step 4: Register Users with Roles
Modify app/Http/Controllers/Auth/RegisterController.php
to assign roles dynamically.
Step 5: Create Middleware for Admin Access
We need middleware to restrict pages to admins only.
1️⃣ Create Admin Middleware
2️⃣ Edit Middleware (app/Http/Middleware/AdminMiddleware.php
)
3️⃣ Register Middleware (app/Http/Kernel.php
)
Step 6: Define Routes for Admin & User
Modify routes/web.php
to define separate routes.
Step 7: Create Admin & User Controllers
Generate controllers for admin and users.
1️⃣ Edit app/Http/Controllers/AdminController.php
2️⃣ Edit app/Http/Controllers/UserController.php
Step 8: Create Login Views for Admin & User
Create view files for admin and user dashboards.
1️⃣ Admin Dashboard View (resources/views/admin/dashboard.blade.php
)
2️⃣ User Dashboard View (resources/views/user/dashboard.blade.php
)
Step 9: Redirect Users After Login
Modify app/Providers/RouteServiceProvider.php
to send admins to /admin/dashboard
and users to /user/dashboard
.
Step 10: Test the Login System
1️⃣ Register a User
-
Go to
/register
-
Create an account
-
Change
role
to'admin'
manually in the database to test the admin login.
2️⃣ Login as an Admin
-
Visit
/login
-
If admin → redirected to
/admin/dashboard
-
If the user → redirected to
/user/dashboard
Summary
✅ Setup Laravel Authentication with Laravel Breeze
✅ Added role
column to users table
✅ Created AdminMiddleware
for role-based access
✅ Defined separate routes for Admin & Users
✅ Created separate login views for Admin & Users
✅ Redirected users to the correct dashboard after login