Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel, change connection in model for one method?

Tags:

php

laravel

I have got a dev database and a live database. I need to return some results from the live database but only for one method within this model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class TableName extends Model
{
    protected $table = 'table_name';

    protected $connection = 'dev';

    public $timestamps = false;

    public static function live($index) {

        $liveId = Settings::where('index', $index)->get()[0];

        $live = new TableName;

        $live->setConnection('live');

        $data = $live::where('index', $liveId->live_index)->get();

        dd($live);

        return $data;

    }
}

If I dd() the $live variable after calling setConnection then it does say that the connection is indeed live. However as soon as I dd() the $data I get the rows from the dev database!

like image 236
Martyn Ball Avatar asked Jan 02 '23 21:01

Martyn Ball


2 Answers

Eloquent provides a nice way to handle multiple connections.

You should just be able to use the on method. For example.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class TableName extends Model
{
    protected $table = 'table_name';

    protected $connection = 'dev';

    public $timestamps = false;

    public static function live($index) {

        $liveId = Settings::where('index', $index)->get()[0];

        $data = self::on('live')->where('index', $liveId->live_index)->get();

        return $data;

    }
}

That should then run the query using the live connection in your database configuration.

like image 156
George Hanson Avatar answered Jan 04 '23 11:01

George Hanson


I have personally haven't done anything like this, but I found out way to do this by following these steps.

In the .env file add these new env variables =>

DB_CONNECTION_2=mysql
DB_HOST_2=127.0.0.1
DB_PORT_2=3306
DB_DATABASE_2=database2
DB_USERNAME_2=root
DB_PASSWORD_2=secret

Now inside the config/database.php file specify the 2nd mysql connection with the previously entered env variables.

'mysql2' => [
    'driver'    => env('DB_CONNECTION_2'),
    'host'      => env('DB_HOST_2'),
    'port'      => env('DB_PORT_2'),
    'database'  => env('DB_DATABASE_2'),
    'username'  => env('DB_USERNAME_2'),
    'password'  => env('DB_PASSWORD_2'),
],

Now you can create a Model for the required table =>

class myModel extends Eloquent {

    protected $connection = 'mysql2';

}

Then you can use it as the regular way will all the Eloquent features in controller methods =>

$newMy = new myModel;
$newMy->setConnection('mysql2');
$newMy = $someModel->find(1);
return $something;

Here is the doc link that you can read about this more.

like image 37
menaka Avatar answered Jan 04 '23 10:01

menaka