【问题标题】:Laravel 4 -> Routes on the same controller with multiple variablesLaravel 4 -> 具有多个变量的同一控制器上的路由
【发布时间】:2013-11-07 03:39:49
【问题描述】:

我在使用 Laravel 时遇到了一些路由问题。我认为是因为我没有采取好的方法但是......

这是我的代码:

Route::group(array('prefix' => 'products'), function()
{
    Route::get('', array('uses'=>'products@index'));
    //show all the products 

    Route::get('{Categorie}',array('uses'=>'products@categorie'))->where('Categorie','^[A-Z][a-z0-9_-]{3,19}$');
    //show the products of this categorie   

    Route::get('{shopname}',array('uses'=>'products@shopname'))->where('shopname','^[a- z][a-z0-9_-]{3,19}$');
     //show the product of this shopname
});

Route::group(array('prefix' => '/products/{:any}'), function()
{
   //no index because productName is not optionnal

    Route::get('{productName}', array('uses'=>'product@getProduct'));
    //the Product controller is now SINGULAR
    //show this product in particular
});

所以它适用于第一组...... mysite.fr/products => 好的 mysite.fr/MyCategorie => 好的 mysite.fr/mashopname => 好的

但是当我添加第二个参数时:

mysite.fr/products/myshopname/myfirstproduct

我收到了一个带有特定消息的错误...

非常感谢您的帮助!

【问题讨论】:

    标签: php laravel laravel-4 laravel-routing


    【解决方案1】:

    这里的问题是这些都是相同的路线。 Laravel 不知道什么可以算作类别、商店名称或任何其他名称。例如,如果我转到/products/test,Laravel 将不知道 test 是类别、商店名称还是产品名称。

    试试这个吧……

    Route::group(array('prefix' => 'products'), function()
    {
        Route::get('/', array('uses'=>'products@index'));
        //show all the products 
    
        Route::get('categorie/{Categorie}',array('uses'=>'products@categorie'))->where('Categorie','^[A-Z][a-z0-9_-]{3,19}$');
        //show the products of this categorie   
    
        Route::get('shopname/{shopname}',array('uses'=>'products@shopname'))->where('shopname','^[a- z][a-z0-9_-]{3,19}$');
        //show the product of this shopname
    
        Route::get('product/{productName}', array('uses'=>'product@getProduct'));
        //the Product controller is now SINGULAR
    });
    

    这样,如果我转到 products/categorie/test,Laravel 会知道我正在寻找 categorie 并能够正确地路由我。

    更新:

    如果Hightech 是一个类别,product_1 是一个产品,您可以使用这样的路由...

        Route::get('category/{categorie}/product/{product}',array('uses'=>'products@categorie'))->where('categorie','^[A-Z][a-z0-9_-]{3,19}$')->where('product','^[A-Z][a-z0-9_-]{3,19}$');
        //show the products of this categorie   
    

    然后 URL 将是 .com/products/category/Hightech/product/product_1。或者你可以把/product/category 拿出来,你可以直接去.com/products/Hightech/product_1

    【讨论】:

    • 我想到了这一点,但我的想法是将商店名称/类别保留在 url 中。就像你继续 .com/products/Hightech/ 然后你继续 .com/products/Hightech/product_1 。我试过这个-> "Route::get('/{:any}/{productName}', array('使用'=>'product@getProduct'));"但仍然是一个错误...
    • 我刚刚更新了答案,这样您就可以使用这样的 URL。
    猜你喜欢
    • 2013-11-05
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2022-01-14
    • 2023-03-13
    • 2013-06-11
    • 2017-04-01
    相关资源
    最近更新 更多