September 19, 2024 Laravel
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.
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.
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.
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
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',
];
}
Next, we need to define the authentication guards and providers for the Admin
model.
config/auth.php
and add the new guard for admin:'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
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.
We now need to create authentication controllers for the admin, similar to the default Laravel Breeze controllers.
php artisan make:controller AdminAuth\LoginController
php artisan make:controller AdminAuth\RegisterController
php artisan make:controller AdminAuth\AuthenticatedSessionController
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.
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>
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');
});
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');
Now that everything is set up, you can test the application:
/admin/register
to register a new admin user./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.
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!
August 10, 2024
August 06, 2024
August 04, 2024
August 05, 2024
August 08, 2024
August 12, 2024
Comments