How to Implement Admin Login Using User Type in Laravel 10
Introduction:
In modern web applications, managing user roles such as admin, vendor, or customer is essential to maintaining security and accessibility. Laravel 10 provides a flexible framework for implementing role-based access control (RBAC) through middleware, custom trust flows, and database properties such as user_type In this case, we create a custom middleware that will control access for different users by adding the user_type field to the user table. We will go over how to set up the system
Prerequisites:
To follow along with this tutorial, you’ll need:
- Laravel 10 installed in your project.
- A database connection configured.
- Basic understanding of Laravel’s authentication system.
Step 1: Add user_type
to the Users Table
First, you need to modify the users
table to include a user_type
column that will help differentiate between admin and regular users.
- Create a migration: Run the following command to create a migration that adds a
user_type
column to yourusers
table:
php artisan make:migration add_user_type_to_users_table --table=users
2. Update the migration: Open the newly created migration file located in database/migrations/
. Inside the up
method, add the user_type
field:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('user_type')->default('user'); // Default value is 'user'
});
}
This will add a user_type
column with a default value of user
to the users
table.
3. Run the migration: Apply this migration to your database by running:
php artisan migrate
After running this, your users
table will have a new column user_type
that can be used to store the role of each user.
Step 2: Seed an Admin User
Next, let’s create a default admin user. You can either modify your user registration logic to allow assigning the user_type
or use database seeders for testing.
- Create a seeder: You can update your
DatabaseSeeder.php
or create a new seeder to insert an admin user. Run this command to create a new seeder:
php artisan make:seeder AdminSeeder
2. Modify the seeder: In database/seeders/AdminSeeder.php
, insert the following code:
use App\Models\User;
use Illuminate\Database\Seeder;
class AdminSeeder extends Seeder
{
public function run()
{
User::create([
'name' => 'Admin User',
'email' => 'admin@example.com',
'password' => bcrypt('password'),
'user_type' => 'admin', // Assign the user type as 'admin'
]);
}
}
3. Run the seeder: Now run the seeder to create the admin user in your database:
php artisan db:seed --class=AdminSeeder
You now have an admin user with the email admin@example.com
and password password
in your database.
Blog Title:
“How to Implement Admin Login Using User Type in Laravel 10”
Introduction:
In modern web applications, managing user roles such as admin, vendor, or customer is crucial for maintaining security and access control. Laravel 10 provides a flexible framework for implementing role-based access control (RBAC) through middleware, custom authentication flows, and database attributes like user_type
. In this article, we’ll walk through how to set up an admin login system by adding a user_type
field to the users
table and creating custom middleware to control access for different types of users.
Prerequisites:
To follow along with this tutorial, you’ll need:
- Laravel 10 installed in your project.
- A database connection configured.
- Basic understanding of Laravel’s authentication system.
Step 1: Add user_type
to the Users Table
First, you need to modify the users
table to include a user_type
column that will help differentiate between admin and regular users.
- Create a migration: Run the following command to create a migration that adds a
user_type
column to yourusers
table:
- bash
- Copy code
php artisan make:migration add_user_type_to_users_table --table=users
- Update the migration: Open the newly created migration file located in
database/migrations/
. Inside theup
method, add theuser_type
field:
- php
- Copy code
public function up() { Schema::table('users', function (Blueprint $table) { $table->string('user_type')->default('user'); // Default value is 'user' }); }
- This will add a
user_type
column with a default value ofuser
to theusers
table. - Run the migration: Apply this migration to your database by running:
- bash
- Copy code
php artisan migrate
After running this, your users
table will have a new column user_type
that can be used to store the role of each user.
Step 2: Seed an Admin User
Next, let’s create a default admin user. You can either modify your user registration logic to allow assigning the user_type
or use database seeders for testing.
- Create a seeder: You can update your
DatabaseSeeder.php
or create a new seeder to insert an admin user. Run this command to create a new seeder:
- bash
- Copy code
php artisan make:seeder AdminSeeder
- Modify the seeder: In
database/seeders/AdminSeeder.php
, insert the following code:
- php
- Copy code
use App\Models\User; use Illuminate\Database\Seeder; class AdminSeeder extends Seeder { public function run() { User::create([ 'name' => 'Admin User', 'email' => 'admin@example.com', 'password' => bcrypt('password'), 'user_type' => 'admin', // Assign the user type as 'admin' ]); } }
- Run the seeder: Now run the seeder to create the admin user in your database:
- bash
- Copy code
php artisan db:seed --class=AdminSeeder
You now have an admin user with the email admin@example.com
and password password
in your database.
Step 3: Create Middleware for Admin Users
Blog Title:
“How to Implement Admin Login Using User Type in Laravel 10”
Introduction:
In modern web applications, managing user roles such as admin, vendor, or customer is crucial for maintaining security and access control. Laravel 10 provides a flexible framework for implementing role-based access control (RBAC) through middleware, custom authentication flows, and database attributes like user_type
. In this article, we’ll walk through how to set up an admin login system by adding a user_type
field to the users
table and creating custom middleware to control access for different types of users.
Prerequisites:
To follow along with this tutorial, you’ll need:
- Laravel 10 installed in your project.
- A database connection configured.
- Basic understanding of Laravel’s authentication system.
Step 1: Add user_type
to the Users Table
First, you need to modify the users
table to include a user_type
column that will help differentiate between admin and regular users.
- Create a migration: Run the following command to create a migration that adds a
user_type
column to yourusers
table:
- bash
- Copy code
php artisan make:migration add_user_type_to_users_table --table=users
- Update the migration: Open the newly created migration file located in
database/migrations/
. Inside theup
method, add theuser_type
field:
- php
- Copy code
public function up() { Schema::table('users', function (Blueprint $table) { $table->string('user_type')->default('user'); // Default value is 'user' }); }
- This will add a
user_type
column with a default value ofuser
to theusers
table. - Run the migration: Apply this migration to your database by running:
- bash
- Copy code
php artisan migrate
After running this, your users
table will have a new column user_type
that can be used to store the role of each user.
Step 2: Seed an Admin User
Next, let’s create a default admin user. You can either modify your user registration logic to allow assigning the user_type
or use database seeders for testing.
- Create a seeder: You can update your
DatabaseSeeder.php
or create a new seeder to insert an admin user. Run this command to create a new seeder:
- bash
- Copy code
php artisan make:seeder AdminSeeder
- Modify the seeder: In
database/seeders/AdminSeeder.php
, insert the following code:
- php
- Copy code
use App\Models\User; use Illuminate\Database\Seeder; class AdminSeeder extends Seeder { public function run() { User::create([ 'name' => 'Admin User', 'email' => 'admin@example.com', 'password' => bcrypt('password'), 'user_type' => 'admin', // Assign the user type as 'admin' ]); } }
- Run the seeder: Now run the seeder to create the admin user in your database:
- bash
- Copy code
php artisan db:seed --class=AdminSeeder
You now have an admin user with the email admin@example.com
and password password
in your database.
Step 3: Create Middleware for Admin Users
To restrict access to certain routes to only admin users, we need to create custom middleware.
- Generate middleware: Run the following command to create the middleware:
php artisan make:middleware AdminMiddleware
2. Modify the middleware logic: In the newly created file app/Http/Middleware/AdminMiddleware.php
, add the following logic to restrict access to users who have user_type
set to 'admin'
:
public function handle($request, Closure $next)
{
if (auth()->check() && auth()->user()->user_type === 'admin') {
return $next($request);
}
return redirect('/home')->with('error', 'Unauthorized access.');
}
3. Register middleware: To make the middleware available for use in your routes, add it to the $routeMiddleware
array in app/Http/Kernel.php
:
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];
Now, the admin
middleware is ready to restrict access to specific routes.
Step 4: Update Routes for Admin Login and Dashboard
Next, we need to set up routes for the admin login page and an admin dashboard.
- Modify
web.php
routes: Inroutes/web.php
, add the following routes:
use App\Http\Controllers\AdminController;
Route::get('/admin/login', [AdminController::class, 'showLoginForm'])->name('admin.login');
Route::post('/admin/login', [AdminController::class, 'login']);
Route::middleware(['auth', 'admin'])->group(function () {
Route::get('/admin/dashboard', [AdminController::class, 'dashboard'])->name('admin.dashboard');
});
Here, we’re creating routes for showing the login form, handling the login submission, and displaying the admin dashboard, but only allowing admins to access the dashboard using the custom admin
middleware.
Step 5: Create the Admin Controller
We now need to implement the logic for the admin login and dashboard in a controller.
- Generate the AdminController: Create a new controller using the following command:
php artisan make:controller AdminController
2. Define the login and dashboard methods: In app/Http/Controllers/AdminController.php
, update the controller with methods for displaying the login form, handling the login request, and displaying the admin dashboard:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AdminController extends Controller
{
public function showLoginForm()
{
return view('admin.login');
}
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
if (auth()->user()->user_type === 'admin') {
return redirect()->route('admin.dashboard');
}
Auth::logout();
return redirect()->route('admin.login')->with('error', 'Unauthorized access.');
}
return redirect()->back()->withErrors('Invalid credentials');
}
public function dashboard()
{
return view('admin.dashboard');
}
}
Step 6: Create Views for Admin Login and Dashboard
Finally, we need views for the login form and the dashboard.
- Admin login view: Create a file at
resources/views/admin/login.blade.php
for the login form:
<h1>Admin Login</h1>
<form method="POST" action="{{ route('admin.login') }}">
@csrf
<div>
<label for="email">Email:</label>
<input type="email" name="email" id="email" required>
</div>
<div>
<label for="password">Password:</label>
<input type="password" name="password" id="password" required>
</div>
<button type="submit">Login</button>
</form>
@if(session('error'))
<p>{{ session('error') }}</p>
@endif
2. Admin dashboard view: Create a file at resources/views/admin/dashboard.blade.php
for the admin dashboard:
<h1>Welcome to the Admin Dashboard</h1>
Conclusion:
Following these steps, you have successfully implemented the admin login option in Laravel 10 using the user_type field on the users table. With the help of custom middleware, only user_type set as administrator can access the admin dashboard, creating a secure and user-based login policy.
You can extend this approach to include additional user roles, such as vendors or customers, to increase the flexibility and security of your application.
Happy coding!