Skip to content
Advertisement

How to use my own pre-existing table for authentication in laravel 8?

I installed auth in laravel 8 but I don’t want to use the default table dedicated for authentication Users because I have my table Users_inf in this case I can’t use migration, Users_inf also has 200 records. Users_inf(user_id, password, user_name,privilege,active,CREATED_AT,UPDATED_AT). CREATED_AT and UPDATED_AT added by me to be compatible with laravel. I am using user_name for login not email. please, any suggestion for that issue.

Advertisement

Answer

The way I see it, you have two choices. Either alter the users table to have those fields, then import the data from one table to another – or, update your User model to use that table. In any case, you have to instruct Laravel to use the user_name field for authentication. Personally I would recommend going the first route, as that’s the “Laravel way”.

Approach 1: Altering the users table

Alter the migration of the users table, something along the lines of this. I would recommend you keep the ID field id rather than specifying your own user_id, as this is – again – the Laravey way of doing things.

Schema::create('users', function (Blueprint $table) {
    $table->id('user_id'); // $table->id();
    $table->string('user_name')->unique();
    $table->string('privilege')->nullable();
    $table->string('password');
    $table->boolean("active")->default(true);
    $table->rememberToken();
    $table->timestamps();
});

Then to move the data over, run the following SQL query

INSERT INTO users (user_id, user_name, privilege, active, password, created_at, updated_at)
    SELECT user_id, user_name, privilege, active, password, created_at, updated_at
    FROM users_inf AS ui
    WHERE NOT EXISTS(SELECT 1
                      FROM users AS u
                      WHERE u.user_name = ui.user_name)

Now you just need to instruct Laravel to use the user_name field, which we cover at the bottom of this answer.

Approach 2: Altering the User model

Laravel lets you specify which table and which field is the primary key, by adding simple properties to the model. Inside your User model class, add the following two lines,

protected $table = 'users_inf';
protected $primaryKey = 'user_id';

For both approaches: Using the user_name field as the login

Simply add the username() method to the User model class that returns the field which Laravel should use to lookup users in the given table.

public function username()
{
    return 'user_name';
}

Laravel will give you so much “for free” and a lot of features will work more seamlessly when using the proper naming conventions. I suggest you follow the Laravel standards and naming conventions, as it will make it easier to work with the framework as a whole.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement