I want to manually authenticate a user in Laravel 5. My application uses 2 databases, which are located on the same server. In my application i already switch connections in the models or query builder, which works perfect.
But now i want to use laravels Auth::attempt
method to login a user. But the credentials for this user are stored in the second database.
In the user model i have: protected $connection = 'first_database';
This is the database it normally should use. But for this 'special' login, i want the user model to use the second_database
.
Is this possible?
What i tried:
\Config::set('database.default', 'second_database');
// Login this user while using the second_database
if(\Auth::attempt(['email'=>\Request::get('email'), 'password'=>\Request::get('password')]))
{
dd('Success');
}
But unfortunately, this doesn't work. I`m using Laravel 5.1
Notice that you can do the following to attempt an authentication:
$this->guard()->attempt([ 'email' => \Request::get('email'), 'password' => \Request::get('password'), ]);
And in a nutshell, your solution will need to utilize the guard()
part:
$this->guard('my-second-database-guard')->attempt([ 'email'=>\Request::get('email'), 'password'=>\Request::get('password') ]);
The steps:
If you take a look at auth.php
you will notice 'provider', and where does provider comes from?
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
Provider comes in this section, same auth.php
:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
So, we could add another User class that utilizes a different connection and use it as a provider for our guard.
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'master-users' => [
'driver' => 'eloquent',
'model' => App\Master\Models\User::class,
],
]
And in the guards section:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'master-web' => [
'driver' => 'session',
'provider' => 'master-users',
],
],
Of course, we have to duplicate the User class:
<?php
namespace App\Master\Models;
use App\Models\User as UserClass;
class User extends UserClass
{
protected $connection = 'second_database';
/**
* Get the guard to be used during authentication.
*
* @return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard('master-web')
}
}
And then we can attempt to authenticate the users like:
$this->guard('master-web')->attempt([ 'email' => \Request::get('email'), 'password' => \Request::get('password'), ]);