I have an application stack in Laravel that we're going to go ahead and switch to a SaaS model. In order to do this, I just assumed I could wrap all my routes in a group with dynamic domain properties, fire a filter, and then observe the $route parameters to make this occur.
I should note that this is actually a Multi-Tenancy application but we've actually decided to separate the databases out for this one.
So here we go:
In my routes.php
file, I've got the following:
Route::group(array('domain' => '{domain}.{tld}', 'before' => 'database.setup'), function()
{
Route::group(array('prefix' => 'backend', 'before' => 'auth'), function () {
//all of my routes
});
});
As you can see from the above, when any route is requested, it's going to the database.setup
filter that I've got defined in filters.php
:
Route::filter('database.setup', function($route, $request){
$domain = $route->getParameter('domain').'.'.$route->getParameter('tld');
$details = DB::table('my_table')->where('domain', '=', $domain)->first();
if($details){
Config::set('database.connections.account', [
'driver' => 'mysql',
'host' => 'my_host',
'database' => Encryption::decrypt($details->db_hash, 'my_salt'),
'username' => 'my_username',
'password' => 'my_password',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'charset' => 'utf8',
]);
//these are things I was doing to get the URL-permalink working.
Config::set('app.url', 'http://' . $domain);
Config::set('app.domain', $domain);
Config::set('session.domain', '.' . $domain);
//This actually works exactly as I've intended
Config::set('database.connections.default', 'account');
DB::setDefaultConnection('account');
}
});
Now initially I thought this was working fine. The correct record was pulled from the table, and the database switched on the fly without issue while destroying the previous instance. Great.
However, I noticed that I've lost all of my model binding relationships in the routes.
A route such as this:
Route::get('/shipping/packages/{package}', 'PackageController@get');
With a model defined as such:
Route::model('package', 'Package');
Unfortunately always results in this:
No query results for model [Package].
Now, if I remove my filter from the Route, everything works fine, but the default database will be used a big nono for my application.
Lastly, all of the permalink structure seems to be completely broken. Instead of seeing my domain when I hover over a link, such as:
http://example.com/shipping/packages/package
I instead see:
%7Bdomain%7D.%7Btld%7D/shipping/packages/package
I have no idea why this is occurring.
I've tried overloading the response object, altering the settings for the site Configuration within the filter, and a host of other things, but I always end up having the same issue in some way or another.
I'd be greatly appreciative if anyone has any clue's on how to solve this issue.