Laravel 12 E-Commerce: Admin and User Authentication

Hi everyone, welcome back to the Laravel E-Commerce Tutorial. In this video, we are going to learn about creating Admin and User Authentication. We will be using the laravel/breeze package, which has already been installed.


1. Database Setup (Users Table Migration)

First, let'screate a migration to add two new columns to the existing users table: one for the phone number and one for the user type.

Create Migration

php artisan make:migration add_phone_and_utype_fields_to_users_table

Update Migration File

Open the created migration file and add the following columns inside the up method:

public function up(): void
{
Schema::table("users",
function (Blueprint $table) {
$table->string("mobile")->unique();
$table->string("utype")->default("USR")->comment("ADM for Admin and USR for User or Customer");
});
}

Refresh Migrations

Run the command to refresh and execute the migration:

Php artisan migrate:refresh

2. Admin Authentication Middleware

Next, we will create a middleware to restrict access to admin-only pages.

Create Middleware

php artisan make:middleware AuthAdmin

Update AuthAdmin.php

Open the app/Http/Middleware/AuthAdmin.php file. Add the necessary dependencies and logic inside the handle method:

use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesSession;
public function handle(Request $request, Closure $next): Response
{
if(Auth::check())
{
if(Auth::user()->utype==="ADM")
{
return $next($request);
}
else{
Session::flush();
return redirect()->route("login");
}
}
else{
return redirect()->route("login");
}
}

3. User Model and Registration Update

Update User Model

Go to the User Model (app/Models/User.php) and add mobile to the $fillable array:

protected $fillable = [
"name",
"email",
" mobile",
"password",
];

Update Registered User Controller

In app/Http/Controllers/Auth/RegisteredUserController.php, update the validation rules and creation logic to include the mobile field (required, string, 10 digits, unique to the users table):

"mobile" => ["required", "string", "digits:10", "unique:users’],
"mobile" => $request->mobile,

4. Add Mobile Input to Registration View

Open resources/views/auth/register.blade.php and add the input field for the phone number:

<div class="mt-4">
<x-input-label for="mobile" :value="__(‘Mobile")" />
<x-text-input id=“mobile" class="block mt-1 w-full" type="text" name="mobile" :value="old("mobile")" required autocomplete="mobile" />
<x-input-error :messages="$errors->get("mobile")" class="mt-2" />
</div>

5. Controllers and Dashboard Views

Create Controllers

Create separate controllers for the User and Admin dashboards:

php artisan make:controller UserController
Php artisan make:controller AdminController

Update Controllers with Index Function

In UserController.php, add the index function:

public function index()
{
return view(“user.index”);
}

In AdminController.php, add the index function:

public function index()
{
return view(“admin.index”);
}

Create Dashboard Views

Inside the resources/views directory, create a user folder and an admin folder. Inside each, create an index.blade.php file.

User Dashboard View (user/index.blade.php):

<x-app-layout>
</x-app-layout>
<h1>User Dashboard</h1>

Admin Dashboard View (admin/index.blade.php):

<x-app-layout>
</x-app-layout>
<h1>Admin Dashboard</h1>

6. Routing and Navigation

Define Routes in web.php

Add the routes for the user dashboard (protected by auth middleware) and the admin dashboard (protected by auth and AuthAdmin middleware):

Route::middleware(["auth"])->group(function(){
Route::get("/account/dashboard", [UserController::class, "index"])->name("user.index’);
)};
Route::middleware(["auth",AuthAdmin::class])->group(function(){
Route::get("/admin", [AdminController::class, "index"])->name("admin.index");
});

Update Layout Navigation

Update the main layout file (e.g., in the navigation dropdown) to link to the appropriate dashboard (Admin or User) based on the authenticated user'sutype, and include links for Login/Logout:

<div class="dropdown">
<a class="action" href="#" role="button" data-bs-toggle="dropdown"><i class="pe-7s-user"></i></a>
<ul class="dropdown-menu dropdown-profile">
@guest
<li><a href="{{ route("login") }}">Login</a></li>
@else
<li>
@if(Auth::user()->utype == "ADM")
<a href="{{ route("admin.index") }}">My Account</a>
@else
<a href="{{ route("user.index") }}">My Account</a>
@endif
</li>
<li>
<form action="{{ route("logout") }}" method="POST">
@csrf
<a href="{{ route("logout") }}" onclick="event.preventDefault();this.closest("form").submit();">Sign Out</a>
</form>
</li>
@endifs
</ul>
</div>

7. Testing and Finalization

Run the application with php artisan serve and go to localhost:8000.

Register two users: one intended for the Admin role and one for a normal User.

  • Admin Registration: Email: admin@surfsidemedia.in, Password: 12345678
  • User Registration: Email: user@surfsidemedia.in, Password: 12345678

Go to phpMyAdmin, browse the users table, and manually edit the record for the admin user, changing the utype to `ADM`.

After logging in with admin credentials, you should see the Admin Dashboard. If you log in with user credentials, you will see the User Dashboard. Attempting to access the `/admin` page with a normal user will redirect the user to the login page due to the middleware.

This completes the setup for Admin and User Authentication for the E-commerce Project.