Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override table prefix for a model

Hello I've in config/database.php a prefix (mysql) like this:

     'prefix' => 'myprefix_',

But I need, only for one model, to use a different prefix like:

     protected $table = 'otherprefix_mytable';

In this way laravel looking for "myprefix_otherprefix_mytable".

Any help?

like image 331
natas Avatar asked Feb 22 '17 14:02

natas


2 Answers

In your app/config/database.php make 2 different connections like

'connections' => array(

        # first prefix
        'mysql1' => array(
            'driver'    => 'mysql',
            'host'      => 'host1',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => 'prefix1',
        ),

        # second prefix
        'mysql2' => array(
            'driver'    => 'mysql',
            'host'      => 'host1',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => 'prefix2',
        ),
    ),

And then later in model you can use different connection

class SomeModel extends Eloquent {    
    protected $connection = 'mysql2';    
}

For more help check this

like image 197
KuKeC Avatar answered Nov 18 '22 17:11

KuKeC


Default table prefix can be overriding in laravel model as following example:


use Illuminate\Support\Facades\Config;

public function __construct(array $attributes = array()) {
    $collection = Config::get('database');
    $collection['connections']['mysql']['prefix'] = 'consultancy_';
    Config::set('database',$collection);
    parent::__construct($attributes);
}
like image 42
Samsher Avatar answered Nov 18 '22 15:11

Samsher