Laravel中的路由顺序很重要

4

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)

可能是在Laravel包中路由声明的顺序问题的重复问题。 - Steve Mitcham
在Laravel包中,路由声明的顺序很重要吗? - Steve Mitcham
1个回答

0

我知道这个问题很老,可能已经过时了,但我认为评论中提到的可能重复的内容并不适用于这个问题。

然而,我找到了以下解决方案来解决这个问题,我也刚遇到了这个问题。

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

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

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

如需更多信息,请参阅官方文档


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接