Ad

Laravel 5 Routes - Group Domains From Rows In Database

- 1 answer

I have a web application that needs to be served on multiple domains. I'm running Laravel 5.1 for this.

In the routes.php file, I'd like to be able to identify which domain the user found the page through, and if that domain is found in a list of useable domains, then pass them over to a particular controller.

The following snippet is from my routes.php:

$temporaryDomainList = \App\Domain::select('domain')->where('status','=','1')->get()->toArray();
// This returns us a 2-d array, with the second dimension just being ['domain','whatever.com'] -
// we want ['whatever.com','whatever2.com'] so let's clean it up...
$domainList = [];
foreach ($temporaryDomainList as $uselessArray) {
    $domainList[] = $uselessArray['domain'];
}

Route::group(['domain' => $domainList], function ($domainList) {
    Route::get('/{linkName}', '[email protected]');
    Route::get('/', function () {
        throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
    });
});

At the moment I get an error enter image description here

Ad

Answer

The problem here is that you're trying to assign an array of domains to the group's domain attribute. You can't do that, the domain attribute is expected to be a string, not an array of strings. When the RouteCollection class tries to concatenate it with another string, you get an:

Array to string conversion exception

To fix this you should create the groups inside the foreach:

$domains = \App\Domain::where('status', '1')->get()->pluck('email');

foreach ($domains as $domain) {
    Route::group(['domain' => $domain], function () {
        Route::get('/{linkName}', '[email protected]');
        Route::get('/', function () {
            abort(404);
        });
    });
}

I've also used pluck to get a collection of domain values fetched from the database, since it's all that's needed here. Also for brevity, calling the abort(404) helper function does essentially the same thing as throwing the NotFoundHttpException exception.


As a side note, you might want to put the route registration in a Service Provider since the routes.php file doesn't seem a good place to put the database logic.

Ad
source: stackoverflow.com
Ad