Laravel 5 multiple database connection.

Published 2 years ago by nanadjei2

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).

Best Answer (As Selected By nanadjei2)
tomopongrac

@nanadjei2

put in 'App/User.php

protected $connection = 'mysql2';
tomopongrac
nanadjei2

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

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

@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');
nanadjei2

@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

@nanadjei2

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

Does your code passed if statement

nanadjei2

@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

@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

@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'?

tomopongrac

@nanadjei2

put in 'App/User.php

protected $connection = 'mysql2';
nanadjei2

@tomo_pongrac , thank you man it worked.......!!!!!!

tomopongrac

@nanadjei2

Great :)

nanadjei2

@tomo_pongrac , please if anything comes up i will let you know. Am very grateful.

tiya

no need to externally create any model.. simply use it and enjoy it

http://laraveldaily.com/multiple-database-connections-in-the-same-laravel-project/

Please sign in or create an account to participate in this conversation.