Php – Laravel, change connection in model for one method

laravelphp

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!

Best Solution

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.

Related Question