【问题标题】:Routing order in Laravel mattersLaravel 中的路由顺序很重要
【发布时间】:2015-03-14 14:18:37
【问题描述】:

Laravel 中的路由顺序重要吗?

我创建了以下路线:

Route::get('authors/new', array('as'=>'new_author', 'uses'=>'AuthorsController@getNew'));
Route::get('authors/{id}', array('as'=>'author', 'uses'=>'AuthorsController@getView'));

在作者控制器中,我有这些:

public function getView($id)
{
    return View::make('authors.view')
        ->with('title', 'Author View Page')
        ->with('author', Author::find($id));
}

public function getNew()
{
    return View::make('authors.new')
        ->with('title', 'Add New Author');
}

当我进入页面 localhost/authors/new 时,它工作正常。

但是,如果我像这样更改路线的顺序:

Route::get('authors/{id}', array('as'=>'author', 'uses'=>'AuthorsController@getView'));
Route::get('authors/new', array('as'=>'new_author', 'uses'=>'AuthorsController@getNew'));

它不再起作用了,它说:

Trying to get property of non-object (View: C:\xampp\htdocs\laravel\app\views\authors\view.blade.php)

【问题讨论】:

标签: php laravel routes


【解决方案1】:

我知道这个问题已经过时并且可能已经过时,但我认为 cmets 中提到的可能重复项不适合这个问题。

不过,我找到了下面这个问题的解决方案,我也遇到过。

将以下约束添加到您的路线,使其看起来像这样:

Route::get('authors/{id}', array('as'=>'author', 'uses'=>'AuthorsController@getView'))
->where('id', '[0-9]+');

这样,Laravel 会先检查参数id 是否为数字。

欲了解更多信息,请see the official documentation

【讨论】:

    猜你喜欢
    • 2018-12-23
    • 2012-12-11
    • 2014-01-19
    • 1970-01-01
    • 2021-10-12
    • 2012-09-28
    • 2012-06-14
    • 1970-01-01
    相关资源
    最近更新 更多