Laravel 动态路由

Laravel dynamic routing

我正在开发电子商务应用程序。根据他们的 url_key(url 的一列),我需要动态 product/category urls。

我正在尝试做这样的事情:

    if (Route::has('route.name')) {
        // go where ever it is intended
    } 
    else {

        $productHelper = new ProductHelper();

        $product = $productHelper->getProductByUrl($url_key);
        if ($product)
            return Redirect::to('product')->with('id', $product->id);
        else {
            $categoryHelper = new CategoryHelper();

            $category = $categoryHelper->getCategoryByUrl($url_key);

            if ($category)
                return Redirect::route('category')->with('id', $category->id);
            else
                return View::make('static.page_not_found');
        }
    }

假设我们有 url 个像:

/关于我们 /联系我们

/sony-bravia-b32(url 产品密钥) /tv-led(url 类别键)

现在我想检查 "routes.php" 文件中是否存在 url,那么它应该转到那个 url(数据就像提交表单一样)

否则,它会检查 url 是否与产品或类别的 url 键匹配,并相应地移动到那里。

有点像 Magento 的行为。我卡在了 if 部分。

您可以使用 routes.php 来做到这一点。

这是您如何操作的示例。在实际应用程序中,您可能需要为每个路由创建单独的控制器来处理应用程序的不同行为。

Routes.php

Route::get('/about-us', function(){
  echo 'About Us';
});

Route::get('/contact-us', function(){
  echo 'Contact Us';
});


Route::get('/{product}/{category}', function($product, $category){
  dd($product,$category); // remove this line and put your business logic here
});

确保将静态 url 置于动态之上。