0

我找了好几个地方都没有结果,所以我想是时候问问专家了。

我正在玩 laravel,但我在路由方面遇到了一些问题。

我有各种 cms 和产品目录,每个目录都不使用页面前缀。

产品可能是“example.com/my-product”,页面可能是“example.com/my-page”

在我的路线中,我想检查 url 是否与页面或产品匹配,或者两者都不匹配,然后根据它重定向到特定的控制器/操作。

目前我有

Route::any('/{slug}', function($slug) {
    $page = App\Models\Page::firstByAttributes(['slug' => $slug]);
    if($page) {
     // go to pagesController@find
    }
})->where('slug', '.*');

为了区分页面和产品很好,我将在 if($page) 之后弹出一个 elseif 进行产品检查,但是一旦我确定 url 指向,我就很难到达 PagesController数据库上的一个页面。

任何帮助将不胜感激。

编辑:

我的页面控制器:

class PagesController extends BaseController {

    public function find()
    {
        echo 'asdaasda'; die;
    }
}

我可以在时尚之后让它工作,但这不是我想要的。我需要 url 保持原样,并且 PagesController 需要处理页面的处理和呈现。我可以让它工作的唯一方法是在路由文件中添加一个 Route::controller('pages', 'PagesController') 然后将 find 函数修改为 getFind ,但这最终会得到一个看起来像示例的 url。 com/pages/find/ 而不是原来的 url,它可能是类似于 example.com/about-us 的东西。

4

2 回答 2

2

尝试这个

Route::any('/{slug}', function($slug) {
    $page = App\Models\Page::firstByAttributes(['slug' => $slug]);
    if($page) {
      return Redirect::action('pagesController@find', array($page));
   }
})->where('slug', '.*');

您还可以考虑使用路由过滤器以更易读的方式实现此目的。

于 2013-10-17T15:33:41.880 回答
0

我不知道这是否是非常糟糕的做法,但我能看到解决此问题的唯一方法是在 routes.php 中执行以下操作。

$url = \URL::current();
$url = explode('/', $url);
$end = end($url);

if($page = App\Models\Page::firstByAttributes(['slug' => $end])) {
    Route::get('/'.$end, 'PagesController@find');
} elseif($product = App\Models\Product::firstByAttributes(['slug' => $end])) {
    Route::get('/'.$end, 'ProductsController@find');
}

这基本上获取了 url 的最后部分,然后检查我们是否有一个带有该 url 的页面并添加该特定页面的路由,如果没有,它会检查我们是否有适合该 url 的产品并添加该产品的路由.

如果有人有更清洁的解决方案,我很想知道。我无法想象 laravel 没有一种基于数据库页面创建路由的方法,而不必为它们都加上“pages/page-url”之类的前缀。

于 2013-10-17T20:24:38.317 回答