Laravel Passport如何使用自定义密码字段user_password替代password?
user_password for Passport Authentication Hey there! Changing the password column name from password to user_password is totally doable—here's a step-by-step guide to get it working with your Passport setup:
1. Rename the Database Column
First, we need to create a migration to rename the existing password column in your users table:
Run this Artisan command to generate the migration file:
php artisan make:migration rename_password_to_user_password_in_users_table
Open the generated file (found in database/migrations/) and update it with the rename logic:
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up() { Schema::table('users', function (Blueprint $table) { $table->renameColumn('password', 'user_password'); }); } public function down() { Schema::table('users', function (Blueprint $table) { $table->renameColumn('user_password', 'password'); }); } };
Execute the migration to apply the change:
php artisan migrate
2. Update the User Model
Laravel's authentication system looks for a password column by default, so we need to tell it to use user_password instead. Add this method to your User model (usually app/Models/User.php):
/** * Get the password for the user. * * @return string */ public function getAuthPassword() { return $this->user_password; }
3. Verify Your Login Method
Looking at your existing login() method in PassportController:
public function login() { if (Auth::attempt(['user_login' => request('login'), 'password' => request('user_password')])) { $user = Auth::user(); $success['token'] = $user->createToken('ToutelaBreizh')->accessToken; return response()->json(['success' => $success], $this->statusCode); // Rest of your code... } }
This should work perfectly now! Here's why:
- The
'user_login'key matches your username field. - The
'password'key inAuth::attempt()holds the plain-text password fromrequest('user_password'). - Laravel will hash this plain text and compare it against the hashed value from
getAuthPassword()(which pulls fromuser_passwordin the database).
Bonus: Update Registration Logic (If Applicable)
If you have a registration flow, make sure you're storing the hashed password in the user_password column instead of the old password column:
use Illuminate\Support\Facades\Hash; // In your registration controller $user = User::create([ 'user_login' => $request->login, 'user_password' => Hash::make($request->user_password), // Add other user fields here ]);
That's it! Your Passport authentication should now work seamlessly with the new user_password column.
内容的提问来源于stack exchange,提问作者JacopoStanchi

