toddddos
toddddos

Reputation: 361

Laravel5 - Changing the name of primary key column with database driver

I am not using Eloquent.

My user table uses userid as primary column name (not id), I have UserItem that implements the Authenticatable interface and my config/auth.php looks like this:

'providers' => [
         'users' => [
             'driver' => 'database',
             'table' => 'user',
         ],
    ],

Everything works when I rename the column to 'id', but if don't do that I get this error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `user` where `id` = 55 limit 1)...

because of this code in my view (it's default, just checks whether to display login/register or logged user menu):

<?php if(auth()->guard()->guest()): ?>

it's this directive:

@guest

Where can I change it so it doesn't look for id but rather userid instead?

Upvotes: 0

Views: 586

Answers (1)

Webdesigner
Webdesigner

Reputation: 1982

With 'driver' => 'database' you are not so flexible as with 'driver' => 'eloquent'.
I can tell you that id is hard coded as part of the database driver and the GenericUser class.

If you really looking for the position where the database driver do the user authentication than you have to look at:
/vendor/laravel/framework/src/Illuminate/Auth/DatabaseUserProvider.php

public function retrieveById($identifier)
{
    $user = $this->conn->table($this->table)->find($identifier);

    return $this->getGenericUser($user);
}

Here we connecting with the database and to retrieve the user by it's identifier. So far so good but this is calling the find method which you will find here:
/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php

public function find($id, $columns = ['*'])
{
    return $this->where('id', '=', $id)->first($columns);
}

You see id is a fixed string for any simple find method used by the database driver. Changing it to userid will cause that you have to chance all your primary keys in your database and of course in all other methods that uses id as well.

The GenericUser has also id as a hard coded value to identify the user, see:
/vendor/laravel/framework/src/Illuminate/Auth/GenericUser.php

public function getAuthIdentifierName()
{
    return 'id';
}

So even if you change all id to userid than you can't update, because everything will be overwritten.

My advice: use Laravel Eloquent if you can, or keep the primary identifier asid.

FYI: I used the Laravel 5.5 Codebase

Upvotes: 1

Related Questions