dongwen9947 2013-10-17 15:20
浏览 68
已采纳

Laravel Routes使用通配符时出现问题

I have looked in quite a few places to no avail so I thought it was time to ask the experts.

I am playing about with laravel and I am having some issues with routing.

I have a cms of sorts and also a product catalogue, each of which uses no prefix to the pages.

A product might be 'example.com/my-product' and a page might be 'example.com/my-page'

In my routes I want to check if the url matches a page or a product or neither and then redirect to a specific controller/action depending on which it is.

currently I have

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

To differentiate between a page and a product is fine, I'll just pop an elseif after the if($page) for the product check but I am stumped as to how to get to the PagesController once I have determined that the url points to a page on the db.

Any help would be massively appreciated.

Edit:

My Pages Controller:

class PagesController extends BaseController {

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

I can get this to work after a fashion but its not what I want. I need the url to remain as it was and the PagesController to handle the processing and rendering of the page. The only way I can get it to work is by adding a Route::controller('pages', 'PagesController') to the routes file then modifying the find function to getFind but that just ends up with a url that looks like example.com/pages/find/ rather than the original url that might have been something along the line of example.com/about-us.

  • 写回答

2条回答 默认 最新

  • dtxb75622 2013-10-17 15:33
    关注

    Try this

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

    You can also consider using route filters to achieve this in a slightly more readable way.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 链接问题 C++LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接