Laravel using wrong DB in multi-database environment
Ad
I have a Laravel project with a local and remote DB. I have these set in the .env
. When trying to access the remote DB, Laravel is attempting to use the local DB and I am getting an error. The crazy thing is that if I remove the password for remote DB in my .env
file, it throws an error about access denied to the remote DB.
I read that if there is an error with the secondary DB that it would revert to the default DB, which looks like what is happening. However, I am connected to the remote DB with Sequel Pro, so I know my connection is good. Here is the .env
:
APP_ENV=local
APP_DEBUG=true
APP_KEY=JnsC2R88qLM6GTnivxLWPKs2ds2dfplI
SITE_URL=http://health.dev
DB_REMOTE_HOST=myhost.cc
DB_REMOTE_DATABASE=databasename
DB_REMOTE_USERNAME=username
DB_REMOTE_PASSWORD=password
DB_LOCAL_HOST=localhost
DB_LOCAL_DATABASE=health
DB_LOCAL_USERNAME=homestead
DB_LOCAL_PASSWORD=secret
And my database.php
:
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_LOCAL_HOST', 'localhost'),
'database' => env('DB_LOCAL_DATABASE', 'forge'),
'username' => env('DB_LOCAL_USERNAME', 'forge'),
'password' => env('DB_LOCAL_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
'mysql_remote' => [
'driver' => 'mysql',
'host' => env('DB_REMOTE_HOST', ''),
'database' => env('DB_REMOTE_DATABASE', ''),
'username' => env('DB_REMOTE_USERNAME', ''),
'password' => env('DB_REMOTE_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
And my Center
model:
<?php
namespace App;
use DB;
use Illuminate\Database\Eloquent\Model;
class Center extends Model
{
protected $table = 'Center';
private $center;
public function __construct()
{
$this->center = DB::connection('mysql_remote')->table($this->table);
}
}
Ad
Answer
Ad
no need to pass in the constructor. You can set the connection via protected property in the model:
class Center extends Model
{
protected $table = 'Center';
protected $connection = 'mysql_remote';
}
Ad
source: stackoverflow.com
Related Questions
Ad
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
Ad