Laravel 中的路由顺序重要吗?
我创建了以下路线:
Route::get('authors/new', array('as'=>'new_author', 'uses'=>'AuthorsController@getNew'));
Route::get('authors/{id}', array('as'=>'author', 'uses'=>'AuthorsController@getView'));
在作者 Controller 中,我有这些:
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)
最佳答案
我知道这个问题很老而且可能过时了,但我认为评论中提到的可能重复项不适合这个问题。
但是,我找到了这个问题的以下解决方案,这也是我刚刚遇到的。
将以下约束添加到您的 route ,使其看起来像这样:
Route::get('authors/{id}', array('as'=>'author', 'uses'=>'AuthorsController@getView'))
->where('id', '[0-9]+');
像这样,Laravel 会先检查参数 id
是否存在是一个数字。如需更多信息,请see the official documentation .
关于php - Laravel 中的路由顺序很重要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27976139/