Laravel e commerce tutorial Part 4: Building the User Authentication System

Part 4: Building the User Authentication System

In this part of the Laravel E-Commerce Tutorial, we’ll focus on building the user authentication system. User authentication is a fundamental aspect of any e-commerce application, allowing users to register, log in, and access personalized features.

4.1 Installing and Configuring Laravel Authentication

Laravel provides a convenient way to scaffold the authentication system with the help of Artisan commands. Let’s start by installing and configuring the Laravel authentication system.

Step 1: Install Laravel Jetstream

If you haven’t already installed Jetstream during the initial setup, run:

bash
composer require laravel/jetstream

Step 2: Install Jetstream Livewire or Inertia (Choose one)

Choose either Livewire or Inertia based on your preference. In this example, we’ll use Livewire:

bash
php artisan jetstream:install livewire

Step 3: Run Migrations

Run the migrations to create the necessary tables:

bash
php artisan migrate

Step 4: Install NPM Dependencies

Install the NPM dependencies and build your assets:

bash
npm install && npm run dev

Step 5: Set Up Jetstream

Configure Jetstream features, such as teams and profile photos, by running:

bash
php artisan jetstream:install livewire

This command will prompt you for additional features. Choose the features that align with your application requirements.

4.2 Customizing User Profiles

With the authentication system in place, let’s customize user profiles to include additional information.

Step 1: Update Users Table

Open the users migration file (create_users_table.php) and add any additional fields you need for user profiles:

php

// database/migrations/YYYY_MM_DD_create_users_table.php

public function up()
{
Schema::create(‘users’, function (Blueprint $table) {
$table->id();
$table->string(‘name’);
$table->string(‘username’)->unique(); // Add a unique username
$table->string(‘avatar’)->nullable(); // Add an avatar field
$table->timestamps();
});
}

Run the migration:

bash
php artisan migrate

Step 2: Update User Model

Update the User model (User.php) to include the new fields:

php

// app/Models/User.php

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
use HasFactory, Notifiable;

protected $fillable = [
‘name’, ’email’, ‘password’, ‘username’, ‘avatar’,
];

// Existing code…

// Define relationships or additional methods as needed
}

Step 3: Update User Profile Views

Customize the user profile views to display and edit the new fields. The views are typically located in the resources/views/profile directory.

4.3 Implementing Role-Based Access Control

Role-based access control (RBAC) allows you to define different roles for users and manage their permissions. In an e-commerce application, roles can include roles like ‘customer’ and ‘admin.’

Step 1: Create Roles Table

Create a migration for the roles table:

bash
php artisan make:migration create_roles_table

Define the roles table schema:

php

// database/migrations/YYYY_MM_DD_create_roles_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateRolesTable extends Migration
{
public function up()
{
Schema::create(‘roles’, function (Blueprint $table) {
$table->id();
$table->string(‘name’)->unique();
$table->timestamps();
});
}

public function down()
{
Schema::dropIfExists(‘roles’);
}
}

Run the migration:

bash
php artisan migrate

Step 2: Create Role Model

Create a Role model to interact with the roles table:

bash
php artisan make:model Role

Define the Role model (Role.php):

php

// app/Models/Role.php

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
use HasFactory;

protected $fillable = [‘name’];

// Define relationships or additional methods as needed
}

Step 3: Assign Roles to Users

Update the User model to include the roles relationship:

php

// app/Models/User.php

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
use HasFactory, Notifiable;

protected $fillable = [
‘name’, ’email’, ‘password’, ‘username’, ‘avatar’,
];

// Existing code…

public function roles()
{
return $this->belongsToMany(Role::class);
}

// Define methods for checking and assigning roles
}

Create methods in the User model to check roles:

php

// app/Models/User.php

// Existing code…

public function hasRole($role)
{
return $this->roles->contains(‘name’, $role);
}

public function assignRole($role)
{
$role = Role::firstOrCreate([‘name’ => $role]);
$this->roles()->sync($role, false);
}

These methods allow you to check if a user has a specific role and assign roles to users.

Step 4: Middleware for Role-Based Access

Create a middleware to handle role-based access:

bash
php artisan make:middleware CheckRole

Define the CheckRole middleware (CheckRole.php):

php

// app/Http/Middleware/CheckRole.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CheckRole
{
public function handle(Request $request, Closure $next, $role)
{
if (!Auth::user()->hasRole($role)) {
abort(403, ‘Unauthorized action.’);
}

return $next($request);
}
}

Register the middleware in the app/Http/Kernel.php file:

php

// app/Http/Kernel.php

protected $routeMiddleware = [
// Existing code…

‘role’ => \App\Http\Middleware\CheckRole::class,
];

Now, you can use the role middleware in your routes to control access based on user roles:

php
Route::middleware(['auth', 'role:admin'])->group(function () {
// Routes accessible only to users with the 'admin' role
});

Congratulations! You’ve successfully implemented the user authentication system in Laravel, customized user profiles, and introduced role-based access control. In the next part of the tutorial, we’ll focus on product management in your e-commerce application. Stay tuned for the next steps!