Php 动态路由

Php 动态路由,php,laravel,Php,Laravel,我希望能够根据从uri收集的数据选择控制器 我有一个类别表和一个子类别表。基本上我有一个如下格式的URL(:any)/(:any)。第一个通配符是城市蛞蝓(即爱丁堡),第二个通配符将是一个类别或子类别蛞蝓 因此,在我的路线中,我搜索带有该路线的类别,如果我找到它,我想使用controller:forsale和method:get_category。如果它不是一个类别,我将查找子类别,如果我在那里找到它,我想使用controller:forsale和method:get_子类别。如果它不是一个子类

我希望能够根据从uri收集的数据选择控制器

我有一个类别表和一个子类别表。基本上我有一个如下格式的URL
(:any)/(:any)
。第一个通配符是城市蛞蝓(即爱丁堡),第二个通配符将是一个类别或子类别蛞蝓

因此,在我的路线中,我搜索带有该路线的类别,如果我找到它,我想使用controller:forsale和method:get_category。如果它不是一个类别,我将查找子类别,如果我在那里找到它,我想使用controller:forsale和method:get_子类别。如果它不是一个子类别,我想继续寻找其他路线

Route::get('(:any)/(:any)', array('as'=>'city_category', function($city_slug, $category_slug){
    // is it a category?
    $category = Category::where_slug($category_slug)->first();
    if($category) {    
        // redirect to controller/method
    } 

    // is it a subcategory?
    $subcategory = Subcategory::where_slug($category_slug)->first();
    if($subcategory) {
        // redirect to controller/method
    }
    // continue looking for other routes
}));
首先,我不知道如何在这里调用控制器/方法,而不实际重定向(从而再次更改url)

第二,这是最好的方法吗?我开始使用
/city\u slug/category\u slug/subcategory\u slug
。但我只想显示
city_slug/category | subcategory_slug
,但我需要一种方法来判断第二个slug是哪一个


最后,在(:any)/(:any)之后可能还有其他URL正在使用,因此我需要它来继续寻找其他路径。

按顺序回答您的问题:
1.不使用不同的
控制器#动作
,您可以使用单个动作并基于第二个slug(类别或子类别),呈现不同的视图(尽管我不喜欢这种方法,请参见#2和#3):

二,。我认为
/city\u slug/category\u slug/subcategory\u slug
比你的方法好得多!你应该用这个
3.同样,你应该修改你的路线。我总是试图让我的路线不会让我困惑,拉雷维尔也不会!!类似于
/products/city/category/subcategory
的内容更加清晰

希望它有帮助(我的代码更像是一个psudocode,它还没有经过测试)

public class Forsale_Controller extends Base_Controller {
  public function get_products($city, $category_slug) {
    $category = Category::where_slug($category_slug)->first();
    if($category) {    
      // Do whatever you want to do!
      return View::make('forsale.category')->with(/* pass in your data */);
    }

    $subcategory = Subcategory::where_slug($category_slug)->first();
    if($subcategory) {
      // Do whatever you want to do!
      return View::make('forsale.sub_category')->with(/* pass in your data */);
    }
  }
}