I am creating a laravel project for which I need one laravel installation and use its instance in sub-domain with separate database. And those separate database's info will not be in config/database.php. It will get from master database and then reconnected to the other database.
I didn't find any proper way to do this.
Do you have any idea on this ?
Thanks for your time.
Laravel supports multiple Database connections. Firstly, define the connections in config/database.php
:
<?php
return array(
'default' => 'default_connection',
'connections' => array(
// domain.com
'default_connection' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'primary_database',
'username' => 'username',
'password' => 'password'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
// sub.domain.com
'subdomain_connection' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'secondary_database',
'username' => 'username',
'password' => 'password'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
),
);
Now to specify which connection your models should use you can set the $connection
property in your models:
<?php
class YourModel extends Eloquent {
protected $connection = 'subdomain_connection';
}
You can set the value of $connection
programatically.
Multi-tenancy is a tricky architecture that needs care to model. There are several ways to achieve this architecture. Some decide to use a single database whiles others prefer to use multiple database(that is in your case).
They both have their pros and cons that you need to consider. There are a lot of factors that need to be taken into consideration before you start modeling your application. eg Virtual host configuration for subdomains, Database migration(rollback all databases when the need be, etc.). I will suggest these two packages that can help you going and give you more insight on how to model your application to suite what you want.
https://github.com/orchestral/tenanti
https://github.com/hyn/multi-tenant
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With