2013-10-17 30 views
0

我看了很多地方无济于事,所以我认为是时候请专家了。Laravel路线使用通配符时的问题

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

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

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

在我的路线我要检查,如果网址相符的网页或产品或不是,然后重定向到一个特定的控制器/操作取决于它是。

目前我有

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

要和页面之间的区分产品是好的,我就弹出如果($页)后ELSEIF的产品检查,但我难倒就如何一旦我确定url指向db上的一个页面,就进入PagesController。

任何帮助将大规模赞赏。

编辑:

我的页面控制器:

class PagesController extends BaseController { 

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

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

回答

1

试试这个

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

您也可以考虑使用路由过滤器在一个稍微更可读的方式来实现这一目标。

+0

感谢这一点,但它给了我一个“未知动作”错误,但在页面控制器中有一个“查找”动作。 –

+0

您可以发布您的PagesController的代码吗? –

+0

@SamParmenter使用PagesController更改pagesController。我认为这是区分大小写的。 –

0

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

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

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

这基本上得到URL的最后一部分,然后再检查,如果我们有与该网址的网页,并添加路由针对特定页面,如果不是,它会检查,如果我们有适合的URL产品并添加该产品的路线。

如果有人有更清洁的解决方案,我很想知道。我无法想象laravel没有基于数据库页面创建路线的方法,而无需将其全部加上“pages/page-url”之类的前缀。