如何在Laravel 5.6中实现多身份认证?
Hey there! Since the multi-auth package you relied on for Laravel 5.5 and earlier doesn't support Laravel 5.6, let's walk through setting up multi-authentication manually. Laravel's core actually has built-in support for this—no third-party packages needed! Let's use an Admin role as an example (you can adapt this for any other user type like Vendor or Customer).
Step 1: Update Authentication Configuration
First, open config/auth.php and add a new guard and provider for your additional user type:
Add a new Guard
Under the guards array, add:
'admin' => [ 'driver' => 'session', 'provider' => 'admins', ],
Add a new Provider
Under the providers array, add:
'admins' => [ 'driver' => 'eloquent', 'model' => App\Admin::class, ],
(Optional) Set Up Password Reset for Admins
If you need password reset functionality for admins, add this under the passwords array:
'admins' => [ 'provider' => 'admins', 'table' => 'password_resets', 'expire' => 60, ],
Step 2: Create the Admin Model & Migration
Generate a new model with a migration file using Artisan:
php artisan make:model Admin -m
Update the Migration File
Open the generated migration (in database/migrations/) and add the necessary fields (match the users table for consistency):
public function up() { Schema::create('admins', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); }
Run the migration to create the admins table:
php artisan migrate
Update the Admin Model
Make sure your App\Admin model uses the Authenticatable trait just like the default User model:
namespace App; 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: Create Admin Authentication Controllers
Copy the default authentication controllers from app/Http/Controllers/Auth/ into a new Admin directory (create app/Http/Controllers/Admin/ first). You'll need:
- LoginController.php
- RegisterController.php (if you want admin registration)
- ForgotPasswordController.php (if you added password reset)
- ResetPasswordController.php (if you added password reset)
Modify the Admin Login Controller
Update app/Http/Controllers/Admin/LoginController.php to use the admin guard and set the correct redirect paths:
namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Support\Facades\Auth; class LoginController extends Controller { use AuthenticatesUsers; // Redirect after successful login protected $redirectTo = '/admin/dashboard'; public function __construct() { $this->middleware('guest:admin')->except('logout'); } // Use the admin guard for authentication protected function guard() { return Auth::guard('admin'); } // Show the admin login form public function showLoginForm() { return view('admin.auth.login'); } // Override logout to redirect to admin login public function logout() { $this->guard()->logout(); return redirect()->route('admin.login'); } }
Adjust Other Controllers (If Needed)
For the RegisterController, ForgotPasswordController, etc., update their namespace, guard references, and view paths similarly. For example, in RegisterController, set the guard to admin and point to the admin registration view.
Step 4: Set Up Admin Routes
Open routes/web.php and add routes for the admin authentication system using a prefix and namespace:
// Admin Authentication Routes Route::prefix('admin')->namespace('Admin')->group(function () { Route::get('login', 'LoginController@showLoginForm')->name('admin.login'); Route::post('login', 'LoginController@login'); Route::post('logout', 'LoginController@logout')->name('admin.logout'); // Optional: Admin Registration Routes // Route::get('register', 'RegisterController@showRegistrationForm')->name('admin.register'); // Route::post('register', 'RegisterController@register'); // Optional: Password Reset Routes // Route::get('password/reset', 'ForgotPasswordController@showLinkRequestForm')->name('admin.password.request'); // Route::post('password/email', 'ForgotPasswordController@sendResetLinkEmail')->name('admin.password.email'); // Route::get('password/reset/{token}', 'ResetPasswordController@showResetForm')->name('admin.password.reset'); // Route::post('password/reset', 'ResetPasswordController@reset')->name('admin.password.update'); }); // Admin Protected Routes (only accessible to logged-in admins) Route::prefix('admin')->namespace('Admin')->middleware('auth:admin')->group(function () { Route::get('/dashboard', 'HomeController@index')->name('admin.dashboard'); // Add other admin-only routes here });
Don't forget to create an Admin/HomeController.php to handle the dashboard view!
Step 5: Create Admin Authentication Views
Copy the default authentication views from resources/views/auth/ into a new admin/auth directory (create resources/views/admin/auth/). Update the following in the copied views:
- Form action URLs: Use admin route names like
{{ route('admin.login') }}instead of{{ route('login') }} - Page titles/headers: Change "Login" to "Admin Login" for clarity
- Any other UI tweaks you want for the admin area
Step 6: Test the Setup
Create a test admin user using Tinker:
php artisan tinker
Then run:
App\Admin::create([ 'name' => 'Test Admin', 'email' => 'admin@example.com', 'password' => bcrypt('your-password-here') ]);
Now you can visit /admin/login, log in with the credentials you just created, and access the admin dashboard at /admin/dashboard.
Key Notes
- Use the
auth:adminmiddleware to protect admin routes (instead of the defaultauthmiddleware which uses thewebguard for regular users) - To check if a user is authenticated as an admin, use
Auth::guard('admin')->check() - You can repeat this process for additional user types (just create new guards, providers, models, controllers, and routes)
内容的提问来源于stack exchange,提问作者sathish R

