Thursday, March 2, 2017

Laravel 5.3 return Auth:user() by uniqueidentifier

It took a while, but I figured out how to succesfully authenticate a user in Laravel 5.3 using a custom user table, with custom username and password fields.

I needed to alter my User model:

protected $table        = 'Contact';    
protected $primaryKey   = 'ContactId';

public function getAuthPassword()
{
    return $this->New_hashedpassword;
}

The LoginController Http\Controllers\Auth\LoginController.php:

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

For testing, I also changed the redirection in the LoginController:

protected function redirectTo()
{
    dd(Auth::user());
}

After a successful login, the correct User model is passed to the browser.

The only problem I face now, is that this custom table uses a MSSQL uniqueidentifier as primary key. So now that when I call Auth::user()->someUserAttribute, my Laravel app throws an error:

[SQL Server]Operand type clash: uniqueidentifier is incompatible with int (SQL: select top 1 * from [Contact] where [Contact].[ContactId] = 7164)

For some reason, the actual ContactID for this user (which is a string "07164BAE-33AE-E511-AE88-000C29C93884") is converted to an int resulting in "7164".

I do not understand why the LoginController can access the Auth::user() without any problem, but anywhere else in the application accessing Auth::user() throws an error.

TIA, Wouter

EDIT

When I edit my User model as Jeff suggests, by adding the getAuthIdentifier and hardcoding my test user's UUID, the Auth::user() object can be accessed successfully. But how do I tell Laravel to convert to ContactId to a string instead of an integer?

public function getAuthIdentifier()
{
    //return $this->ContactId;      
    return '07164BAE-33AE-E511-AE88-000C29C93884';
}



via mokum

Advertisement