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.
Okay, I've figured out what the issue is.
I've apparently not read over the documentation well enough. If you walk through the router group call it will eventually invoke mergeGroup(), which in this particular function, you can observe the following code:
$new['where'] = array_merge(array_get($old, 'where', []), array_get($new, 'where', []));
Here, we can see that they're just using a stack to keep track of these values, so the literal interpretation of {domain}.{tld} was being pushed onto the stack.
This was working fine initially because my filter actually grabs them explicitly:
$domain = $route->getParameter('domain').'.'.$route->getParameter('tld');
To resolve this, I just needed to create my own helper function that would grab the $host (this is an extremely rudimentary implementation, but should help for clarity)
$domain = get_domain();
Route::group(array('domain' => $domain, 'before' => 'database.setup'), function()
Then in my helpers file, I've added the get_domain() function:
if ( ! function_exists('get_domain'))
{
function get_domain()
{
$url_parts = parse_url(Request::root());
return $url_parts['host'];
}
}
Then I can simply call get_domain() in my filter as well and it'll always be in sync:
Route::filter('database.setup', function($route, $request){
$domain = get_domain();
This works perfectly now.
Related
Laravel has really nice features of routing which made our life so comfortable. I am so curious about this Route::group() wrapper. How does it work and how does Roue class inside group wrapper get the information at group parameters. Is it maintain any global variable?
Route::group([
'prefix' => 'audiobook',
'middleware' => 'auth:api',
'namespace' => 'Api\Audiobook'
], function () {
Route::get('latest', 'AudioController#LatestAudioBook');
});
Here's the code that actually does it!
It's not modifying a "global" variable, or at least whether it's global or not is only incidentally relevant in that it's a design decision.
The routes are stored in a Router object, and you can read how the code works at the link above.
I am trying to create a wildcard route to host multiple domains. It works as long as I don't use a country specific domain name.
Route::group([
'domain' => 'admin.{domain}.{tld}',
'namespace' => 'Admin\Pages'
], function () {
require base_path('routes/web/admin/pages.php');
});
The main area to look at 'domain' => 'admin.{domain}.{tld}'
This works for domains on a single extension, eg. domain.com but it does not work for domains with a country code eg. domain.com.au. What is the wildcard for catching both the tld and country code so that both domains will work and not just one.
This example works for instance 'domain' => 'admin.{domain}.com.au' but is not dynamic.
Ok so I worked it out.
admin.{domain}.{tld}.{cc}
It doesn't matter what they are named as long as their is enough periods to catch all of the extensions. They get saved to variables such as $domain, that can be used inside the closures.
I have a controller function that gets called and returns a redirect_url to an AJAX request.
This is created using this call:
URL::to('model/configuration/'. $data->id )
In both production and local, there is a "prefix" url before the "model/" part of the URL. For example, the final url may look like part1/part2/model/configuration/8.
On production, the "part1/part2" part is not being generated by the URL::to() call.
Any idea why this is occurring and how to fix it?
full route definitions:
Route::post('model/configuration/{order_id}', ModelController#configUpdate');
Route::get('model/configuration/{order_id}', 'ModelController#model');
You mention a 'prefix' in your question, but I didn't see any in your route definitions. Regardless, I don't think URL::to() actually verifies that a route exists, and you can use it to make non-existent links to within your application (for whatever good that will do you).
I would suggest for you to instead name your route, and then you can leverage the URL::route() method instead:
Route::group(['prefix' => 'test'], function() {
Route::get('test2', [ 'as' => 'testing', function() {
var_dump(URL::route('testing'));
}]);
});
This will output the following URL:
string 'http://server.com/test/test2' (length=28)
I'm seeing an issue with Laravel 4 when I have two routes pointing to the same action, one within a group and one just "loose" in the routes.php file.
<?php
// Routes.php
Route::group(array('domain' => '{subdomain}.domain.com'), function()
{
Route::get('profile/{id}/{name}', 'ProfileController#index');
});
Route::get('profile/{id}/{name}', 'ProfileController#index');
// Template.blade.php
Jim Smith
The template links to: currentsubdomain.domain.com/profile/%7Bid%7D/%7Bname%7D instead of the expected behaviour of swapping the ID and name for 123 and JimSmith respectively.
If I comment out, the first route (the one within the group), the code works as expected. Why does adding this additional route break the URL generation? Is there a way to work around this? Am I missing something obvious?
P.s. For those wondering why I need this route in two places it's so I can optionally generate the url with the subdomain using URL::action('ProfileController#index' array('subdomain' => 'james', 'id' => 123, 'name' => 'JimSmith');
The problem is that you don't have names/aliases for the routes so it's defaulting to the first one it comes across.
Consider this an alternate route structure:
Route::group(array('domain' => '{subdomain}.domain.com'), function() {
Route::get('profile/{id}/{name}', [
'as' => 'tenant.profile.index',
'uses' => 'ProfileController#index'
]);
});
Route::get('profile/{id}/{name}', [
'as' => 'profile.index',
'uses' => 'ProfileController#index'
]);
Now that you have these routes named, you can do:
{{ URL::route('profile.index', [123, 'jSmith']) }}
Or alternatively:
{{ URL::route('tenant.profile.index', ['subdomain', 123, 'jSmith']) }}
As just an added extra, you could only have this route defined once, then in all the controller methods you'd have something like:
public function index($subdomain = null, $id, $name) { }
Then you can just simply pass www through as the subdomain and have some code somewhere that discounts the www.domain.com domain from certain actions.
Multi-tenancy (if that is indeed what you're after) isn't easy and straight forward but there are some methods used to tackle certain parts. I'm actually planning on writing a tutorial regarding it, but for now I hope this helps somewhat.
Currently my site is designed to serve up multiple subdomains like this:
Route::group(array('domain' => 'site1'.AppHelper::getDomain()), function(){
Route::get('{state?}/{variant?}', array("uses" => 'Site1Controller#showIndex'));
});
Route::group(array('domain' => 'site2'.AppHelper::getDomain()), function(){
Route::get('{state?}/{variant?}', array("uses" => 'Site2Controller#showIndex'));
});
Route::group(array('domain' => 'site3'.AppHelper::getDomain()), function(){
Route::get('{state?}/{variant?}', array("uses" => 'Site3Controller#showIndex'));
});
Now I want to write some tests that crawl these pages checking for specific content. Unfortunately, the only documentation I can find on the Symfony DomCrawler for subdomains tells me to do this (let's say this is on line 312 of my test):
$crawler = $this->$client->request('GET', '/', array(), array(), array(
'HTTP_HOST' => 'site1.domain.dev',
'HTTP_USER_AGENT' => 'Symfony/2.0',
));
Unfortunately when I run PHPUnit and it gets to this test I see this:
1) SiteTest::testSite1ForContent
Symfony\Component\HttpKernel\Exception\NotFoundHttpException:
/var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php:1429
/var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php:1050
/var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php:1014
/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:576
/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:597
/var/www/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/Client.php:81
/var/www/vendor/symfony/browser-kit/Symfony/Component/BrowserKit/Client.php:339
/var/www/app/tests/SiteTest.php:312
So what is it that I'm not understanding here? The site1.domain.dev definitely resolves normally and has no issues that I can see. It seems to be a problem specific to trying to force the header for the subdomain.
Even apart from a solution, how do I debug this properly? I want to figure out why it's not working/where it's failing since this is my first attempt at writing tests.
I started a blank project that just tried to handle this with subdomain routes and it worked perfectly. I realized the issue had to be with what I wrote.
Turns out the issue was actually with a helper I wrote to retrieve the domain. It was trying to access $_SERVER vars that weren't available to the tests when running. Having that return a dev domain if it couldn't retrieve the values solved my issue.
Try this one:
public function refreshApplication()
{
parent::refreshApplication();
$this->client = $this->createClient(
array('HTTP_HOST' => 'site1.domain.dev'));
}
public function testSomething()
{
$crawler = $this->client->request('GET', '/something');
}