0

我知道当您在 Laravel 中执行此操作时:

Route::get('news/read/{year}/{month}/{date}/{title}/{id}', 'PageController@index_page');

我们可以{var}在控制器中使用所有名称作为参数。但是,如果我只想在控制器中使用{id}and而不是所有这些怎么办?{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,但它从and$id读取。我能想到的唯一解决方案是将路线的顺序更改为,但我试图保持与前一个相同的格式,这可能吗?{year}{month}news/read/{title}/{id}/{year}/{month}/{date}

4

1 回答 1

1

首先,这似乎是错误的

public function index_page($year=null, $month=date, $date=null, $title=null, $id=null)

请记住,默认参数的顺序必须作为函数的最后一个参数 - 请查看此处的 PHP 手册示例以获取详细信息。我假设您将 $month=date 拼错为 $month='some_default_date_value' ?

其次,回答您的问题,您在这里至少有两个选择:

A. 为不同的参数计数或顺序路由到不同的方法

//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 文档中的路由和参数

于 2013-11-25T08:55:58.563 回答