据我所知,当你在Laravel中这样做时:
Route::get('news/read/{year}/{month}/{date}/{title}/{id}', 'PageController@index_page');
我们可以使用所有{var}
名称作为控制器中的参数。但是,如果我只想在控制器中使用{id}
和{title}
而不是所有这些?
这是我目前的控制人员:
public function index_page($year=null, $month=date, $date=null, $title=null, $id=null) {
$plugin_files = $this->addJqueryPlugin(array('unslider'));
$data['css_files'] = $this->addCSS(array('styles'));
$data['js_files'] = $this->addJS(array('main'), false);
$data['css_plugin'] = $plugin_files['css_files'];
$data['js_plugin'] = $plugin_files['js_files'];
if (is_null($id)) {
$data['title'] = 'Homepage';
$this->layout->content = View::make('page.home', $data);
}
else {
$data['isModal'] = true;
$data['title'] = ucwords(str_replace("-", " ", $title . '--' . $id));
$this->layout->content = View::make('page.home', $data);
}
}
我尝试只放$title
和$id
,但它改为{year}
和{month}
。我能想到的唯一解决方案是将路由的顺序更改为news/read/{title}/{id}/{year}/{month}/{date}
,但我试图保持前一个格式,是否可能?
答案 0 :(得分:1)
首先,这似乎是错误的
public function index_page($year=null, $month=date, $date=null, $title=null, $id=null)
请记住,默认参数的顺序必须是函数的最后一个参数 - 有关详细信息,请查看PHP Manual example here。我假设你拼错了$ month = $ month ='some_default_date_value'的日期?
第二,回答你的问题,你在这里至少有两个选择:
一个。路由到不同的方法,用于不同的参数计数或订单
//Routes
//different routes for different params
Route::get('news/read/{year}/{month}/{date}/{title}/{id}', 'PageController@indexFull');
Route::get('news/read-id/{id}/{title}', 'PageController@indexByIdAndTitle');
Route::get('news/read-some-more/{month}/{date}/{id}/{title}/{year}', 'PageController@indexByWeirdParamsOrder');
//Controller
//different methods for different routes
public function indexByIdAndTitle($id, $title){ return $this->indexFull($id,$title); }
public function indexFull($id, $title, $year=null, $month=null, $date=null) { ... }
public function indexByWeirdParamsOrder($month, $date, $id, $title, $year) { ... }
B中。更改路线中的参数顺序并使用可选的参数/默认值
//Routes
Route::get('news/read/{id}/{title}/{year?}/{month?}/{date?}', 'PageController@indexFull');
//Controller
public function indexFull($id, $title, $year=null, $month=null, $date=null) { ... }
最后但并非最不重要的,请检查Laravel docs for routing and parameters。