📅  最后修改于: 2023-12-03 14:43:44.694000             🧑  作者: Mango
Laravel Auth User_id is a tutorial that teaches you how to use the user_id
instead of the default id
field for user authentication in Laravel. The tutorial is aimed at intermediate level Laravel developers who are comfortable with working with Laravel's authentication system.
Before proceeding with this tutorial, you should have a basic understanding of Laravel's authentication system. You should also have Laravel installed on your machine, along with a database of your choice.
The first step is to create a migration that will add the user_id
field to the users
table in your database. To do this, navigate to your project's root directory and run the following command:
php artisan make:migration add_user_id_to_users_table --table=users
This will create a new migration file in the database/migrations
directory. Open the migration file and modify it as follows:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedBigInteger('user_id')->default(0)->after('id');
$table->unique('user_id');
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('user_id');
});
}
In this migration, we've added a new column named user_id
to the users
table. We've also set the column's default value to 0
and made it unique.
Next, we need to modify the User
model to use the user_id
field for authentication instead of the default id
field. Open the User
model and modify it as follows:
use Illuminate\Contracts\Auth\Authenticatable;
class User extends Model implements Authenticatable
{
// ...
public function getAuthIdentifierName()
{
return 'user_id';
}
// ...
}
In this code, we've implemented the Authenticatable
contract, which is necessary for the User
model to be used for authentication. We've also overridden the getAuthIdentifierName
method to return user_id
instead of id
.
Now that the User
model has been modified to use user_id
instead of id
for authentication, we need to modify the LoginController to reflect this change. Open the LoginController
and modify the username
method as follows:
protected function username()
{
return 'user_id';
}
This will tell Laravel to use the user_id
field instead of the default email
field for user authentication.
In this tutorial, we've learned how to use the user_id
instead of the default id
field for user authentication in Laravel. We modified the users
table migration to include a user_id
field, modified the User
model to use user_id
for authentication, and modified the LoginController to reflect this change. We hope you found this tutorial helpful!