How to Implement Admin Login Using User Type in Laravel 10

Yash Kumar Prasad
7 min readOct 9, 2024

--

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.

  1. Create a migration: Run the following command to create a migration that adds a user_type column to your users 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.

  1. 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.

  1. Create a migration: Run the following command to create a migration that adds a user_type column to your users table:
  • bash
  • Copy code
  • php artisan make:migration add_user_type_to_users_table --table=users
  1. Update the migration: Open the newly created migration file located in database/migrations/. Inside the up method, add the user_type field:
  • php
  • Copy code
  • public function up() { Schema::table('users', function (Blueprint $table) { $table->string('user_type')->default('user'); // Default value is 'user' }); }
  1. This will add a user_type column with a default value of user to the users table.
  2. 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.

  1. 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
  1. 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' ]); } }
  1. 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.

  1. Create a migration: Run the following command to create a migration that adds a user_type column to your users table:
  • bash
  • Copy code
  • php artisan make:migration add_user_type_to_users_table --table=users
  1. Update the migration: Open the newly created migration file located in database/migrations/. Inside the up method, add the user_type field:
  • php
  • Copy code
  • public function up() { Schema::table('users', function (Blueprint $table) { $table->string('user_type')->default('user'); // Default value is 'user' }); }
  1. This will add a user_type column with a default value of user to the users table.
  2. 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.

  1. 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
  1. 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' ]); } }
  1. 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.

  1. 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.

  1. Modify web.php routes: In routes/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.

  1. 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.

  1. 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!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Yash Kumar Prasad
Yash Kumar Prasad

Written by Yash Kumar Prasad

Full-stack developer with a passion for crafting robust web solutions. Experienced in creating scalable applications that prioritize user experience.

No responses yet

Write a response