vlauciani's avatar

Laravel 5.2 - Authentication (only) on different DB connection

Hi All

What is the best approach to use different connection (for example a dedicated sqlite) only for Auth DB?

I've used the default php artisan make:auth but I do not understand what I need to change to choice different DB connection ONLY for Auth database.

Setting:

class User extends Authenticatable
{
    protected $connection = 'sqlite';
. . .

into User.php Model, It works for login but not for register and for Forgot your password

Thank you.

0 likes
1 reply
vlauciani's avatar

I don't If this is the best solution, but adding:

DB::setDefaultConnection('sqlite');

line in the __construct() method, it works.

AuthController.php file:

<?php

namespace App\Http\Controllers\Auth;

use DB;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        DB::setDefaultConnection('sqlite');
        $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
    }
. . .

PasswordController.php

<?php

namespace App\Http\Controllers\Auth;

use DB;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;

class PasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    /**
     * Create a new password controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        DB::setDefaultConnection('sqlite');
        $this->middleware('guest');
    }
}
1 like

Please or to participate in this conversation.