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

shrutiupari's avatar

Laravel Login using id from different database

I have so far changed the config/database.php file and even the .env file and set it to my 2 of the databases. But I am not able to login using the id. Can anybody please help me.

0 likes
37 replies
Sergiu17's avatar

Make sure to clear cache and config

php artisan cache:clear
php artisan config:clear

Also, you you are using php artisan serve, stop it and start it again

1 like
shrutiupari's avatar

Yes I have done it. But not getting how to and where to do the changes. I have created separate login page and then I am confused as to where should I write the query such that I must be able to login only if user exists in the other database.

shrutiupari's avatar
{{ __('Login') }}
            <div class="card-body">
                <form method="POST" action="{{ route('employeelogin') }}">
                    @csrf

                    <div class="form-group row">
                        <label for="tgi" class="col-sm-4 col-form-label text-md-right">{{ __('Emp TGI') }}</label>
                        <div class="col-md-6">
                            <input id="TGI" type="text" class="form-control{{ $errors->has('TGI') ? ' is-invalid' : '' }}" name="TGI" value="{{ old('TGI') }}" required autofocus>

                            @if ($errors->has('TGI'))
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $errors->first('TGI') }}</strong>
                                </span>
                            @endif
                        </div>
                    </div>

                    <div class="form-group row">
                        <label for="Password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>

                        <div class="col-md-6">
                            <input id="Password" type="Password" class="form-control{{ $errors->has('Password') ? ' is-invalid' : '' }}" name="Password" required>

                            @if ($errors->has('Password'))
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $errors->first('Password') }}</strong>
                                </span>
                            @endif
                        </div>
                    </div>

                    <div class="form-group row mb-0">
                        <div class="col-md-8 offset-md-4">
                            <button type="submit" class="btn btn-primary">
                                {{ __('Login') }}
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

The view file

shrutiupari's avatar

@SERGIU17 - It should be other database table. Thanks I will check the video and let you know.

shrutiupari's avatar

@MUNAZZIL - <?php

namespace App\Http\Controllers\Auth;

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

class LoginController extends Controller { /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */

use AuthenticatesUsers;

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

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('guest')->except('logout');
}

}

siangboon's avatar

don't think you need to change the config/database.php nor the view file, just change the database in the .env will allow you to access to different database. Does the user exist in your second database or the password correct?

siangboon's avatar

try to reset the password for the user in the 2nd database using tinker or create a new one to try login.

munazzil's avatar

After config your database do you run below command,

   php artisan key:generate
shrutiupari's avatar

namespace App\Http\Controllers;

use Illuminate\Http\Request; use DB; use Auth; use App\Model\User; use App\Models\EmployeeMaster;

class AppController extends Controller { // public function __construct() {

}

public function showLoginForm(){

    return view('employeelogin');
}

public function masterlogin(Request $request) {
    
    $this->validate($request,[
        'tgi' => 'required|tgi|exists:tools_bta.emp_username_db',
        'pass' => 'required|pass|exists:tools_bta.emp_username_db',
    ]);

    if(EmployeeMaster::attempt(['tgi' => $request->tgi, 'pass' => $request->pass])){
        return "Logged in successfully";
    }else{
        return "Something went wrong";
    }
}

}

Snapey's avatar

do it step by step.

using dd() or dump() are you getting to the attempt

shrutiupari's avatar

I did in a similar fashion as its done for normal login. Only difference is that I created separate controller and wrote the above functions. I tried to fetch data from 2 databases only if they match and show in datatables, which is working completely fine.

shrutiupari's avatar

Its showing error saying please fill in the details.

Snapey's avatar

Your field names are TGI and Password but you are validating tgi and password so you are not getting past form validation. Nothing to do with authenticating against another database.

shrutiupari's avatar
<?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 index()
    {
        # code...
        return view('login');
    }

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

    //$database = LegonUser::on('mysql2')->select('*')->where($user_data ,'=',         $user_data)->get();
    $legonModel = new LegonUser;
    $legonDB = \DB::connection('mysql_external');
    $logindata = $legonDB->table('emp_username_db')->get();

    $user_data = array(
          'tgi' => $input['tgi'],
          'pass' => $input['pass']
        );

    if (Auth::attempt($user_data)) {
        print_r($user_data);
        // return redirect('/');
       }else {
        return redirect()->back()->withErrors($user_data);
      }
        
   
}
munazzil's avatar

Have you check your HomeController.php and change the below function according to your redirect page,

  public function index()
    {
      return view('employeelogin');
    }
shrutiupari's avatar

I will show the Entire code you can check it. User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    protected $connection = 'mysql_external';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $primaryKey = 'id';
    protected $fillable = [
        'id', 'emp_id', 'tgi', 'pass',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'pass',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */    
}
 
LegonUser.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Authenticatable; 
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 = 'mysql_external';
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'emp_username_db';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['emp_id', 'tgi', 'pass'];

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

    public function user() {
        return $this->belongsTo('App\User','tgi','tgi');
    }
}
shrutiupari's avatar
<?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 index()
    {
        # code...
        return view('login');
    }

    public function LegonSignin() {
    $input = Request::all();
          $user_data = [
          'tgi' => $input['tgi'],
          'pass' => $input['pass']
        ];

    //$database = LegonUser::on('mysql2')->select('*')->where($user_data ,'=',         $user_data)->get();
    $legonModel = new LegonUser;
    $legonDB = \DB::connection('mysql_external');
    $logindata = $legonDB->table('emp_username_db')->select('tgi', 'pass', 'emp_id')->where('tgi', '=', $input['tgi'])->get();

        if ($logindata) {
            print_r($logindata);
            // return redirect('/');
           }else {
            return redirect()->back()->withErrors($user_data);
          }
        
   
}

    public function getTest()
    {
        $db_ext = \DB::connection('mysql_external');
        $countries = $db_ext->table('emp_username_db')->select('tgi', 'pass')->get();
        print_r($countries);
    }

} 

HomeController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('/home');
    }
}

I have done changes in config/database.php and config/auth.php as suggested in this https://laracasts.com/discuss/channels/eloquent/laravel-5-multiple-database-connection link. The login.blade.php remains the same but with different values passed as shown in the LegonUserController.php.

munazzil's avatar

Your missing to define the table name in user.php,

   protected $table = 'users';
Snapey's avatar

@munazzil thats the default behaviour. No need to include it. Not know by now?

1 like
siangboon's avatar

it's better to show the actual error message or screenshot for each step you tested... your "not working" can mean many possibilities

I suspect you custom the create user method without hashing the password...

1 like
shrutiupari's avatar

I am trying to login using emp id and password which is in another database table. I am still facing issues.

aliya's avatar

There is some error in code in LegonSignin function

Next

Please or to participate in this conversation.