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条)

报告相同问题?