0

I have developed a project using Laravel 5.2 and I used 2 MySQL connections and configured as given below in config.database.php.

'mysql1' => [
            'driver' => 'mysql',
            'host' => 'localhost',
            'port' => '3306',
            'database' => 'main_data',
            'username' => 'root',
            'password' => 'root',
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],
        'mysql2' => [
            'driver' => 'mysql',
            'host' => 'localhost',
            'port' => '3306',
            'database' => 'second',
            'username' => 'root',
            'password' => 'root',
            'charset' => 'utf8_table',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],

And the model that I want to use second database connection is given below.

use Illuminate\Database\Eloquent\Model as Eloquent;

class package extends Eloquent {

    //use HybridRelations;
    protected $connection = 'mysql2';
    protected $table = 'PACKAGE';
...

But when I tried to create a new package in controller using package::create(data). it gives error Base table or view not found: 1146 Table 'main_data.package' doesn't exist' in ...

It seems the model connected to the default connection and when I search the only solution I could found is add protected $connection = 'mysql2'; which I already did.

Please help me to solve this issue.

2
  • 1
    Maybe you need to play with the config:cache? Commented Aug 20, 2019 at 14:27
  • @mohammad.kaab I tried to clean all the Laravel cache but still same. Commented Aug 21, 2019 at 4:34

1 Answer 1

1

The $connection attribute in on the Illuminate\Database\Eloquent\Model::class

change your Package::class to extend it

use Illuminate\Database\Eloquent\Model;

class package extends Model {

    //use HybridRelations;
    protected $connection = 'mysql2';
    protected $table = 'PACKAGE';
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry I could not not mention that I extend the same class as use Illuminate\Database\Eloquent\Model as Eloquent;. I'll edit the question
@VikumDheemantha i can't reproduce your issue on a simple Model::create(). There is a bug in laravel 5.2 with relation not having their proper connection loaded but not with direct create. Anyway, try cycling through you table and assign each attribute then call ->save()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.