0

I would have to make many modifications to be able to transfer my laravel project with a single database that has many query builders and eloquent to a project that supports more than one database?

I understand that once a new database is installed it is necessary to use:

connection('mysql2')

When consulting a database, do we tend to change the whole project with this sentence? specifying the connection in each place?

Victor Nuñez
  • 119
  • 2
  • 12

3 Answers3

2

You can add a $connection property to your Eloquent models to specify the database connection there. This way you don't need to update your queries.

protected $connection = 'connection-name';
Jerodev
  • 32,252
  • 11
  • 87
  • 108
2

Migration with multiple connections

public function up()
{
    Schema::connection('mysql-2')->create('user_details', function (Blueprint $table) {
        //........
    });
}

public function down()
{
  Schema::connection('mysql-2')->dropIfExists('user_details');
}

Handle Relationship with multiple database connections

UserDetail.php //mysql-2 (connection-2)

class UserDetail extends Model
{
    protected $connection = 'mysql-2';

    public function user()
    {
        return $this->setConnection('mysql')
                    ->belongsTo(User::class);
    }
}

User.php //mysql (connection-1) //default connection

class User extends Model
{
    //with default connection

    public function detail()
    {
        return $this->setConnection('mysql-2')
                    ->hasOne(UserDetail::class);
    }
}

You don't need to a specified connection in a controller for retrieving/delete/insert data

bhavinjr
  • 1,663
  • 13
  • 19
1

I Understand that you are asking basically how to change database.

For whole project: you can edit mysql connection details in your .env file.

You can also use 2 databases with 1 project , you can learn how to do that from this question which has been already answered: How to use multiple databases in Laravel

I am sorry if i didn't understand your question. Let me know if it helps you.

Amir
  • 721
  • 6
  • 21
  • Not exactly, my question goes to how much code I would have to modify already in a project already created with a single database, so that my project supports multiple databases, Sorry for my not so good English – Victor Nuñez Mar 11 '19 at 12:17
  • Yes for that you can visit the question i added the link of, in the answer above ^. The person who answered it has provided many different ways to switch between databases , from 1 line code each time to 5 - 10 line of code once. – Amir Mar 11 '19 at 12:20
  • 1
    I am glad you understand , if you have any problem understanding the code , let me know i will assist you. Have a nice day buddy. – Amir Mar 11 '19 at 12:24