0

How to connect two database in laravel-5 and how to get data from db.

I know two one thing for that

In config/database set like this.

    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'larashop'),
        'username'  => env('DB_USERNAME', 'root'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

 'mysql2' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST', 'localhost'),
            'database'  => env('DB_DATABASE', 'larashop2'),
            'username'  => env('DB_USERNAME', 'root'),
            'password'  => env('DB_PASSWORD', ''),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],

2 Answers 2

1

Using Query you can define a connection on the Query Builder:

$users = DB::connection('mysql2')->select('your query');

Using Eloquent You can also define which connection to use in your Eloquent models as well!

<?php

class SomeModel extends Eloquent {

    protected $connection = 'mysql2';

}

You can also define the connection at runtime via the setConnection method.

<?php

class SomeController extends BaseController {

    public function someMethod()
    {
        $someModel = new SomeModel;

        $someModel->setConnection('mysql2');

        $something = $someModel->find(1);

        return $something;
    }

}
Sign up to request clarification or add additional context in comments.

2 Comments

This code is okk but Remove connection code from .evn.
1

I have find the issue of connect 2 database in laravel.

If any body wants two work with 2 database then config as par above suggestion and remove database configuration from .env file which is located at root.

I have tried and I am working with 2 database.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.