Home > Database > Mysql Tutorial > How Can I Use Multiple Databases in Laravel?

How Can I Use Multiple Databases in Laravel?

Patricia Arquette
Release: 2024-12-21 20:10:56
Original
465 people have browsed it

How Can I Use Multiple Databases in Laravel?

Using Multiple Databases in Laravel

Laravel's versatility extends to handling multiple databases simultaneously. Follow these steps to accomplish this:

Defining Connections

Use .env >= 5.0:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=mysql_database
DB_USERNAME=root
DB_PASSWORD=secret

DB_CONNECTION_PGSQL=pgsql
DB_HOST_PGSQL=127.0.0.1
DB_PORT_PGSQL=5432
DB_DATABASE_PGSQL=pgsql_database
DB_USERNAME_PGSQL=root
DB_PASSWORD_PGSQL=secret
Copy after login

In config/database.php:

'mysql' => [
    'driver' => env('DB_CONNECTION'),
    'host' => env('DB_HOST'),
    'port' => env('DB_PORT'),
    'database' => env('DB_DATABASE'),
    'username' => env('DB_USERNAME'),
    'password' => env('DB_PASSWORD'),
],

'pgsql' => [
    'driver' => env('DB_CONNECTION_PGSQL'),
    'host' => env('DB_HOST_PGSQL'),
    'port' => env('DB_PORT_PGSQL'),
    'database' => env('DB_DATABASE_PGSQL'),
    'username' => env('DB_USERNAME_PGSQL'),
    'password' => env('DB_PASSWORD_PGSQL'),
],
Copy after login

Without .env <= 4.0:

In app/config/database.php:

return array(
    'default' => 'mysql',
    'connections' => array(
        # Primary/Default database connection
        'mysql' => array(
            'driver' => 'mysql',
            'host' => '127.0.0.1',
            'database' => 'mysql_database',
            'username' => 'root',
            'password' => 'secret'
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
        ),

        # Secondary database connection
       'pgsql' => [
            'driver' => 'pgsql',
            'host' => 'localhost',
            'port' => '5432',
            'database' => 'pgsql_database',
            'username' => 'root',
            'password' => 'secret',
            'charset' => 'utf8',
            'prefix' => '',
            'schema' => 'public',
        ]
    ),
);</p>
<p><strong>Schema / Migration</strong></p>
<p>Specify the connection using the connection() method:</p>
<pre class="brush:php;toolbar:false">Schema::connection('pgsql')->create('some_table', function($table)
{
    $table->increments('id'):
});
Copy after login

Or, define a connection at the top:

protected $connection = 'pgsql';
Copy after login

Query Builder

$users = DB::connection('pgsql')->select(...);
Copy after login

Model

(Laravel >= 5.0)

Set the $connection variable in your model:

class ModelName extends Model { // extend changed

    protected $connection = 'pgsql';

}
Copy after login

(Laravel <= 4.0)

class SomeModel extends Eloquent {
    protected $connection = 'pgsql';
}
Copy after login

Eloquent

Transaction Mode

DB::transaction(function () {
    DB::connection('mysql')->table('users')->update(['name' => 'John']);
    DB::connection('pgsql')->table('orders')->update(['status' => 'shipped']);
});</p>
<p>or</p>
<pre class="brush:php;toolbar:false">DB::connection('mysql')->beginTransaction();
try {
    DB::connection('mysql')->table('users')->update(['name' => 'John']);
    DB::connection('pgsql')->beginTransaction();
    DB::connection('pgsql')->table('orders')->update(['status' => 'shipped']);
    DB::connection('pgsql')->commit();
    DB::connection('mysql')->commit();
} catch (\Exception $e) {
    DB::connection('mysql')->rollBack();
    DB::connection('pgsql')->rollBack();
    throw $e;
}
Copy after login

You can also specify the connection at runtime:

class SomeController extends BaseController {
    public function someMethod()
    {
        $someModel = new SomeModel;
        $someModel->setConnection('pgsql'); // non-static method
        $something = $someModel->find(1);
        $something = SomeModel::on('pgsql')->find(1); // static method
        return $something;
    }
}
Copy after login

Relationship Considerations

Establishing relationships across databases is possible but requires careful handling. It relies on the specific database and settings used.

The above is the detailed content of How Can I Use Multiple Databases in Laravel?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template