Laravel 12 Authentication for Inventory
Management System
This document outlines the implementation of authentication for an Inventory Management
System using Laravel 12, including user registration, login, logout, password reset, and role-
based access control. The system uses Laravel Breeze for scaffolding and MySQL for the
database.
Prerequisites
PHP 8.2 or higher
Composer
MySQL database
Laravel 12 installed (composer create-project laravel/laravel inventory-
system)
Node.js and npm (for compiling frontend assets)
Step 1: Install Laravel Breeze
Laravel Breeze provides a minimal and simple starting point for authentication.
1. Install Breeze:
2. composer require laravel/breeze --dev
3. Run the Breeze installation command and select the Blade stack:
4. php artisan breeze:install blade
5. Compile frontend assets:
6. npm install && npm run dev
7. Migrate the database to create the users table:
8. php artisan migrate
Step 2: Configure the Environment
1. Update the .env file with your database and mail settings:
2. DB_CONNECTION=mysql
3. DB_HOST=127.0.0.1
4. DB_PORT=3306
5. DB_DATABASE=inventory_system
6. DB_USERNAME=root
7. DB_PASSWORD=
8.
9. MAIL_MAILER=smtp
10. MAIL_HOST=smtp.mailtrap.io
11. MAIL_PORT=2525
12. MAIL_USERNAME=your-mailtrap-username
13. MAIL_PASSWORD=your-mailtrap-password
14. MAIL_ENCRYPTION=tls
15. Generate the application key:
16. php artisan key:generate
Step 3: Add Role-Based Access Control
Modify the users table to include a role column for role-based access (Admin, Manager, Staff).
1. Create a migration to add the role column:
2. php artisan make:migration add_role_to_users_table --table=users
3. Edit the migration file (e.g.,
database/migrations/2025_06_16_XXXXXX_add_role_to_users_table.php):
4. use Illuminate\Database\Migrations\Migration;
5. use Illuminate\Database\Schema\Blueprint;
6. use Illuminate\Support\Facades\Schema;
7.
8. return new class extends Migration
9. {
10. public function up(): void
11. {
12. Schema::table('users', function (Blueprint $table) {
13. $table->enum('role', ['admin', 'manager', 'staff'])-
>default('staff');
14. });
15. }
16.
17. public function down(): void
18. {
19. Schema::table('users', function (Blueprint $table) {
20. $table->dropColumn('role');
21. });
22. }
23. };
24. Run the migration:
25. php artisan migrate
26. Update the User model (app/Models/User.php) to include the role column:
27. namespace App\Models;
28.
29. use Illuminate\Foundation\Auth\User as Authenticatable;
30. use Illuminate\Notifications\Notifiable;
31.
32. class User extends Authenticatable
33. {
34. use Notifiable;
35.
36. protected $fillable = [
37. 'name',
38. 'email',
39. 'password',
40. 'role',
41. ];
42.
43. protected $hidden = [
44. 'password',
45. 'remember_token',
46. ];
47.
48. protected $casts = [
49. 'email_verified_at' => 'datetime',
50. 'password' => 'hashed',
51. ];
52. }
Step 4: Create Middleware for Role-Based Access
1. Generate a middleware for role checking:
2. php artisan make:middleware CheckRole
3. Edit the middleware (app/Http/Middleware/CheckRole.php):
4. namespace App\Http\Middleware;
5.
6. use Closure;
7. use Illuminate\Http\Request;
8. use Symfony\Component\HttpFoundation\Response;
9.
10. class CheckRole
11. {
12. public function handle(Request $request, Closure $next, ...
$roles): Response
13. {
14. if (!auth()->check() || !in_array(auth()->user()->role,
$roles)) {
15. abort(403, 'Unauthorized access.');
16. }
17.
18. return $next($request);
19. }
20. }
21. Register the middleware in bootstrap/app.php:
22. use App\Http\Middleware\CheckRole;
23.
24. return Application::configure(basePath: dirname(__DIR__))
25. ->withRouting(
26. web: __DIR__.'/../routes/web.php',
27. commands: __DIR__.'/../routes/console.php',
28. health: '/up',
29. )
30. ->withMiddleware(function (Middleware $middleware) {
31. $middleware->alias([
32. 'role' => CheckRole::class,
33. ]);
34. })
35. ->withExceptions(function (Exceptions $exceptions) {
36. //
37. })->create();
Step 5: Protect Routes with Role Middleware
Update routes/web.php to protect routes based on user roles. Example:
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\ProductController;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::middleware(['auth', 'verified'])->group(function () {
Route::get('/dashboard', [DashboardController::class, 'index'])-
>name('dashboard');
// Admin-only routes
Route::middleware('role:admin')->group(function () {
Route::resource('products', ProductController::class);
});
// Manager and Admin routes
Route::middleware('role:admin,manager')->group(function () {
Route::get('/reports', [ReportController::class, 'index'])-
>name('reports.index');
});
});
require __DIR__.'/auth.php';
Step 6: Create a Dashboard Controller
1. Generate a dashboard controller:
2. php artisan make:controller DashboardController
3. Edit app/Http/Controllers/DashboardController.php:
4. namespace App\Http\Controllers;
5.
6. use Illuminate\Http\Request;
7.
8. class DashboardController extends Controller
9. {
10. public function index()
11. {
12. $user = auth()->user();
13. return view('dashboard', ['user' => $user]);
14. }
15. }
16. Update the dashboard view (resources/views/dashboard.blade.php) to display role-
based content:
17. @extends('layouts.app')
18.
19. @section('content')
20. <div class="container">
21. <h1>Welcome, {{ $user->name }}!</h1>
22. <p>Your role: {{ ucfirst($user->role) }}</p>
23.
24. @if($user->role === 'admin')
25. <a href="{{ route('products.index') }}" class="btn btn-
primary">Manage Products</a>
26. @endif
27.
28. @if(in_array($user->role, ['admin', 'manager']))
29. <a href="{{ route('reports.index') }}" class="btn btn-
secondary">View Reports</a>
30. @endif
31. </div>
32. @endsection
Step 7: Customize Authentication Views
Laravel Breeze generates Blade views in resources/views/auth/. Customize these files (e.g.,
login.blade.php, register.blade.php) to match the Inventory Management System’s
design.
1. Example: Add a role selection field to the registration form
(resources/views/auth/register.blade.php):
2. <!-- Add this inside the form -->
3. <div>
4. <x-input-label for="role" :value="__('Role')" />
5. <select id="role" name="role" class="mt-1 block w-full rounded-md
border-gray-300 shadow-sm">
6. <option value="staff">Staff</option>
7. <option value="manager">Manager</option>
8. <!-- Restrict admin role to prevent public selection -->
9. </select>
10. <x-input-error :messages="$errors->get('role')" class="mt-2" />
11. </div>
12. Update the RegisterController to handle the role` field. Since Breeze uses actions
in Laravel 12, modify the registration logic by creating a custom controller:
13. php artisan make:controller Auth/RegisterController
14. Edit app/Http/Controllers/Auth/RegisterController.php:
15. namespace App\Http\Controllers\Auth;
16.
17. use App\Http\Controllers\Controller;
18. use App\Models\User;
19. use Illuminate\Auth\Events\Registered;
20. use Illuminate\Http\Request;
21. use Illuminate\Support\Facades\Auth;
22. use Illuminate\Support\Facades\Hash;
23. class RegisterController extends Controller
24. {
25. public function create()
26. {
27. return view('auth.register');
28. }
29.
30. public function store(Request $request)
31. {
32. $request->validate([
33. 'name' => ['required', 'string', 'max', '255'],
34. 'email' => ['required', 'string', 'email', 'max', '255',
'unique', 'users'],
35. 'password' => ['required', 'confirmed', 'min', '8'],
36. 'role' => ['required', 'in', 'staff', 'manager'], //
Restrict admin role
37. ], ]);
38.
39. $user = User::create([
40. 'name' => $request->name,
41. 'email' => $request->email,
42. 'password' => Hash::make($request->password),
43. 'role' => $request->role,
44. ]);
45.
46. event(new Registered($user));
47.
48. Auth::login($user);
49.
50. return redirect()->route('dashboard');
51. }
52. }
53. Update routes/web.php to use the custom controller:
54. use App\Http\Controllers\Auth\RegisterController;
55.
56. Route::get('register', [RegisterController::class, 'create'])-
>middleware('guest')->name('register');
57. Route::post('guest', [registerController::class, 'create')-
>middleware('store')->name('store');
Step 8: Seed the Database
Create a seeder to add an admin user for testing.
1. Edit database/seeders/DatabaseSeeder.php:
2. use App\Models\User;
3. use Illuminate\Support\Facades\Hash;
4. use Illuminate\Database\Seeder;
5.
6. class DatabaseSeeder extends Seeder
7. {
8. public function run(): void
9. {
10. User::create([
11. 'name' => 'Admin User',
12. 'email' => '[email protected]',
13. 'password' => Hash::make('password'),
14. 'role' => 'admin',
15. ]);
16. }
17. }
18. Run the seeder:
19. php artisan db:seed
Step 9: Test the Authentication System
1. Start the server:
2. php artisan serve
3. Access the application at http://localhost:8000.
4. Test the following:
o Register a user with role "Staff" or "Manager."
o Log in with the admin user (
[email protected], password: password).
o Verify role-based access:
Admin: Access product management routes.
Manager: Access reports.
Staff: Limited access (e.g., dashboard only).
o Test password reset via email (use Mailtrap to verify emails).
Step 10: Security Enhancements
Enable email verification by adding middleware to protected routes:
Route::middleware(['auth', 'verified'])->group(function)); {
// Routes
});
Sanitize inputs using Laravel’s validation (built into Breeze).
Use HTTPS in production to secure data transmission.
Implement rate limiting for login attempts (Laravel 12 includes this by default).
Conclusion
The authentication system for the Inventory Management System, built with Laravel 12 and
Breeze, provides secure user management with role-based access control. The setup is modular,
allowing for further customization (e.g., adding two-factor authentication or OAuth).