Laravel 5路由 - 来自数据库中行的组域

时间:2015-12-28 22:05:43

标签: php laravel routing laravel-5

我有一个需要在多个域上提供的Web应用程序。我正在为此运行Laravel 5.1。

routes.php文件中,我希望能够确定用户找到该网页的域名,以及是否在可用域列表中找到该域名,然后将其传递过来到特定的控制器

以下代码段来自我的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}', 'RetargetController@retarget');
    Route::get('/', function () {
        throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
    });
});

目前我收到错误enter image description here

1 个答案:

答案 0 :(得分:1)

此处的问题是,您尝试将一组域分配给该组的domain属性。你不能这样做,domain属性是expected to be a string,而不是字符串数组。当RouteCollection类尝试使用另一个字符串concatenate it时,您会得到:

  

数组到字符串转换异常

要解决此问题,您应该在foreach

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

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

我还使用pluck来获取从数据库中提取的domain值的集合,因为这里需要所有这些值。同样为了简洁起见,调用abort(404)辅助函数与抛出NotFoundHttpException异常基本相同。

作为旁注,您可能希望将路由注册放在Service Provider中,因为routes.php文件似乎不是放置数据库逻辑的好地方。

相关问题