【问题标题】:Laravel 4.2 and URLSLaravel 4.2 和 URL
【发布时间】:2016-07-11 12:54:15
【问题描述】:

我将获得如下所示的网址

      whatever.com/products/accessories/1
      whatever.com/products/amplifiers/2
      whatever.com/products/speakers/3

我到处阅读和搜索,但不知道如何使用一条 Route::

如果我执行以下操作

      whatever.com/products/1
      whatever.com/products/2
      whatever.com/products/3

我可以使用以下路线::

    Route::model('product', 'Product');

    Route::get('products/{product}', function(Product $product)
    {
        return View::make('product', array('product' => $product->toArray()));
    });

但这并不能制作非常友好的网址

提前致谢

【问题讨论】:

    标签: laravel-4 routes


    【解决方案1】:

    经过几个小时的搜索,我找到了以下解决方案

    Route::get('products/{p1?}/{p2?}/{p3?}/{p4?}', 'ProductController@index');

    【讨论】:

    • 虽然你可以使用像这样的可选参数,但它仍然没有解决你的中间“产品类别”参数没有意义的事实,因为你可以输入任何东西,它会仍然匹配。请检查我的解决方案,这将允许两个参数仍然被强制执行并具有意义。
    【解决方案2】:

    为了强制执行中间参数并使其有意义,同时仍以传递的最终 ID 为基础,您可以将 Route Model Binding 与解析器函数一起使用。传递给解析器函数的第二个参数是Illuminate\Routing\Route 的实例,如果您检查它的API,您会看到它有一个parameter() 方法,可以让您获取any 的值路由中的参数。这使您可以访问这两个参数并从中构建查询。

    Route::bind('product', function($value, $route){
        $category = $route->parameter('category');
        $product = Product::where(['id' => $value, 'category' => $category])->first();
        return $product ?: 'Not found';
    });
    
    Route::get('products/{category}/{product}', function($category, $product)
    {
        return View::make('product', array('product' => $product->toArray()));
    });
    

    请注意,如果没有结果,我将返回一个字符串 'Not found',但您可以返回任何内容。这允许您强制执行中间参数实际上是有意义的,以便 whatever.com/products/amplifiers/2 将返回一个真实的结果,而 whatever.com/products/fake/2 不会。

    【讨论】:

    • 这正是我想要的。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2015-01-14
    • 2015-06-05
    • 2014-12-03
    • 2015-01-12
    • 1970-01-01
    • 2019-01-10
    • 2017-12-10
    • 2015-01-11
    相关资源
    最近更新 更多