Oto Shavadze
Oto Shavadze

Reputation: 42863

How to change default table name `users` to custom name

I want to change default table name users to another name, say lara_users.

Searched several resources and many of them says that "you need change table name in config/auth.php file like so: 'table' => 'lara_users'.

In Laravel 5.4, there is not clearly defined (for me at least) where is that 'table' key? I changed here:

...
'providers' => [

    'users' => [
       'driver' => 'database',
       'table' => 'lara_users',
    ],
],
...

Though, after that, when I try to log in, application trows an error: Undefined table: 7 ERROR: relation "users" does not exist (I use postgresql).

P.S.

I already changed table name to lara_users in migrations, it works and creates that table successfully.

Upvotes: 2

Views: 2697

Answers (3)

madeny
madeny

Reputation: 483

OK. change users to lara_users in user migration.

Now that you change the default table name. go to User model User.php under

app directory, add this in User class

 protected $table = 'lara_users';

Now go to RegisterController.php edit the email key:

 'email' => 'required|string|email|max:255|unique:users',

to this

'email' => 'required|string|email|max:255|unique:lara_users',

That's it.

Upvotes: 5

Prashant Barve
Prashant Barve

Reputation: 4325

If you want to add lara_ in all the table name then you can add the name by adding prefix in the database.php. if you add prefix it will add to all tables and you do not need to change anything else, laravel itself search for the table with this prefix.

    'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => 'lara_',
        'strict' => true,
        'engine' => null,
    ],

Please note that it will work with eloquent query if you use DB::table(''), then you need to add the prefix in all queries. use $prefix = \DB::getTablePrefix(); for prefix to make it dynamic for DB queries.

Upvotes: 7

Omi
Omi

Reputation: 4017

Add this code in your auth.php

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
        'table' => 'lara_users',
    ],
],

After that run artisan migrate command.

If your App\Users modal have set $table variable then change it to

protected $table = 'lara_users';

Upvotes: 2

Related Questions