Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nanadjei2's avatar

Laravel 5 multiple database connection.

I am developing a system that fetches data from two databases. I want to do a login function but direct the function to the other database(mysql2 in config/database) to the other database and not default database(mysql). This is my config/database.php

  # Knust primary database connection
 'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => 'hofsa_knust',
        'username'  => 'root',
        'password'  => '',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

         # Legon primary database connection
         'mysql2' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => 'hofsa_legon',
        'username'  => 'root',
        'password'  => '',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

This is my controller

 <?php

 namespace App\Http\Controllers;
 use Illuminate\Support\Facades\Validator;
 use Illuminate\Support\Facades\Hash;
 use Illuminate\Support\Facades\Auth;
 use App\Http\Requests;
 use App\Http\Controllers\Controller;
 use App\Http\Requests\CreateUserRequest;
 use UxWeb\SweetAlert;
 use App\LegonUser;
 use Request;
 use Alert;
 use DB;
 class LegonUserController extends Controller
    {
  public function LegonSignin() {
   $input = Request::all();
  $user_data = [
  'username' => $input['username'],
  'password' => $input['password']
];

//$database = LegonUser::on('mysql2')->select('*')->where($user_data ,'=',         $user_data)->get();
$legonModel = new LegonUser;
$legonDB = $legonModel->setConnection('mysql2');

if ($legonDB) {
  if (Auth::attempt($user_data)) {
    //Alert::success('You Have Successfully Signed In', 'Great !');
    alert()->success('You Have Successfully Signed In', 'Great !')->autoclose(2500);
    return redirect('/');
  } else {
    return redirect()->back()->withErrors($user_data);
  }
}

} }

This is my Eloquent Model

 <?php

namespace App;

use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class LegonUser extends Model implements AuthenticatableContract, CanResetPasswordContract { use Authenticatable, CanResetPassword;

/**
 * The database name used by the model.
 *
 * @var string
 */
protected $connection = 'mysql2';
/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'users';

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = ['firstname', 'lastname', 'username', 'nickname', 'password'];

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = ['password', 'remember_token'];

} After all these, it still goes to the default database and not the custom one(mysql2).

0 likes
16 replies
nanadjei2's avatar

@tomo_pongrac, do i have to do the this in the controller?

 Schema::connection('mysql2')->create('some_table', function($table)
  {
$table->increments('id'):
 });
tomopongrac's avatar

@nanadjei2

No, that code is for creating tables

https://laravel.com/docs/5.2/migrations

I think that you only have to put this code in model for auth user

protected $connection = 'mysql2';

in this code try this

  if (Auth::attempt($user_data)) {
    //Alert::success('You Have Successfully Signed In', 'Great !');
    alert()->success('You Have Successfully Signed In', 'Great !')->autoclose(2500);
    return redirect('/');
  } else {
    return redirect()->back()->withErrors($user_data);
  }

and remove

$legonModel = new LegonUser;
$legonDB = $legonModel->setConnection('mysql2');
1 like
nanadjei2's avatar

@tomo_pongrac, yes, that was that i was thinking but it looks like all the tutorials i have seen does that so i thought it was included. ok i have done that you asked me to do but it is still not working.

tomopongrac's avatar

@nanadjei2

Strange, i have tested this method and it works (on Laravel 4.2)

Does your code passed if statement

nanadjei2's avatar

@tomo_pongrac , yes and this is it. Do i have to do anything inside the controller?

 public function LegonSignin() {
     $input = Request::all();

     $user_data = [
       'username' => $input['username'],
        'password' => $input['password']
     ];


       if (Auth::attempt($user_data)) {
          //Alert::success('You Have Successfully Signed In', 'Great !');
          alert()->success('You Have Successfully Signed In', 'Great !')->autoclose(2500);
          return redirect('/');
        } else {
          return redirect()->back()->withErrors($user_data);
       }
   }
tomopongrac's avatar

@nanadjei2

are you sure that the settings for the connection is correct and that the auth method is accurate (that you can see in config/auth.php; 'model' => 'name of method')

try:

public function LegonSignin() {
     $username = Request::input('username');
    $password = Request::input('password');

       if (Auth::attempt(['username' => $username, 'password' => $password])) {
          return "Log in";
        } else {
          return "Failed";
       }
   }

nanadjei2's avatar

@tomo_pongrac , ooh i now get it in the config/auth.php, i have this

      'model' => 'App\User::class'

And the model i want to target is 'App/someUser.php' so in this case, how do i do it? Or can i delete the 'someUser' to use the default 'User' which is 'App/User.php'?

shrutiupari's avatar

I tried in a similar way but still no luck. Please help

dakotavanderson's avatar

Did you try the official Laravel method from here https://laravel.com/docs/7.x/database#using-multiple-wpdatabase-connections

When using multiple connections, you may access each connection via the connection method on the DB facade. The name passed to the connection method should correspond to one of the connections listed in your config/database.php configuration file:

$users = DB::connection('foo')->select(...);

You may also access the raw, underlying PDO instance using the getPdo method on a connection instance:

$pdo = DB::connection()->getPdo();

Please or to participate in this conversation.