Laravel Breeze Multi-Auth Tutorial: Step-by-Step Guide

September 19, 2024   Laravel

Laravel Breeze Multi-Auth Tutorial: Step-by-Step Guide

Laravel Breeze is a simple, minimal authentication package that provides a starting point for authentication in Laravel applications. However, in many real-world applications, you might need to handle multiple authentication types, such as administrators and regular users. In this tutorial, we’ll explore how to extend Laravel Breeze to support multi-authentication, allowing you to have different user roles and guards.

Prerequisites:

  • You should have basic knowledge of Laravel.
  • You must have Laravel Breeze installed in your application.

Step 1: Install Laravel Breeze

If you haven't installed Laravel Breeze yet, you can do so by running the following command:

composer require laravel/breeze --dev

Then, install the necessary scaffolding for your Laravel application:

php artisan breeze:install

This command will generate simple authentication controllers and views. Now, run the following command to migrate the default tables and get started:

php artisan migrate npm install && npm run dev

Now, test the application. You should have the default user authentication working.

Step 2: Add Admin Guard and Model

To implement multi-authentication, we need to differentiate between user roles, such as admin and user. First, we will add an admin model and guard.

  1. Create the Admin model and migration:
php artisan make:model Admin -m

This will create a new Admin model and migration file. Open the migration file (located in database/migrations/) and add necessary fields for the admin:

Schema::create('admins', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

Run the migration:

php artisan migrate
  1. Update the Admin model:

Open the Admin.php model and configure it as follows:

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class Admin extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];
}

Step 3: Define Admin Guard and Providers

Next, we need to define the authentication guards and providers for the Admin model.

  1. Open config/auth.php and add the new guard for admin:
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
],
  1. Define the admin provider:
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],

    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Models\Admin::class,
    ],
],

This configuration allows Laravel to know that we want to authenticate Admin users using the newly defined admin guard and the Admin model.

Step 4: Create Admin Authentication Controllers

We now need to create authentication controllers for the admin, similar to the default Laravel Breeze controllers.

  1. Generate the controllers:
php artisan make:controller AdminAuth\LoginController
php artisan make:controller AdminAuth\RegisterController
php artisan make:controller AdminAuth\AuthenticatedSessionController
  1. Define the logic for login and registration:

For the LoginController and RegisterController, copy the basic structure from the user authentication controller but modify it to use the admin guard:

// Admin Login Controller
namespace App\Http\Controllers\AdminAuth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    public function showLoginForm()
    {
        return view('admin.login');
    }

    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if (Auth::guard('admin')->attempt($credentials)) {
            return redirect()->intended('/admin/dashboard');
        }

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ]);
    }

    public function logout(Request $request)
    {
        Auth::guard('admin')->logout();
        return redirect('/admin/login');
    }
}

For the RegisterController, follow a similar process to handle admin registration.

Step 5: Create Views for Admin Authentication

You will need to create separate views for admin login and registration. Create a new folder resources/views/admin, and inside this folder, create login.blade.php and register.blade.php.

For example, here’s a basic admin login form:

<form method="POST" action="{{ route('admin.login') }}">
    @csrf
    <div>
        <label>Email</label>
        <input type="email" name="email" required autofocus>
    </div>

    <div>
        <label>Password</label>
        <input type="password" name="password" required>
    </div>

    <div>
        <button type="submit">Login</button>
    </div>
</form>

Step 6: Add Admin Routes

In your routes/web.php file, add the following routes for admin login and registration:

Route::prefix('admin')->name('admin.')->group(function () {
    Route::get('login', [App\Http\Controllers\AdminAuth\LoginController::class, 'showLoginForm'])->name('login');
    Route::post('login', [App\Http\Controllers\AdminAuth\LoginController::class, 'login']);
    Route::post('logout', [App\Http\Controllers\AdminAuth\LoginController::class, 'logout'])->name('logout');

    Route::get('register', [App\Http\Controllers\AdminAuth\RegisterController::class, 'showRegistrationForm'])->name('register');
    Route::post('register', [App\Http\Controllers\AdminAuth\RegisterController::class, 'register']);
    
    Route::get('/dashboard', function () {
        return view('admin.dashboard');
    })->middleware('auth:admin')->name('dashboard');
});

Step 7: Protect Admin Routes with Middleware

Make sure that the admin routes are protected using the auth:admin middleware. This ensures that only authenticated admin users can access certain routes like the admin dashboard.

Route::get('/dashboard', function () {
    return view('admin.dashboard');
})->middleware('auth:admin')->name('dashboard');

Step 8: Testing the Application

Now that everything is set up, you can test the application:

  1. Visit /admin/register to register a new admin user.
  2. Visit /admin/login to log in as an admin.

Once logged in, you should be redirected to the admin dashboard. Similarly, the regular user authentication should still work separately.

Conclusion

In this tutorial, we walked through how to implement multi-authentication in Laravel Breeze by adding an admin authentication system alongside the default user authentication. By defining multiple guards, providers, and routes, you can easily manage different user roles in your application.

Stay tuned for more tutorials on advanced Laravel features!

 


Comments


Write a Comment