php - Laravel 中的路由顺序很重要

标签 php laravel routes

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/

相关文章:

php - php查询从表中获取行后得到一个随机值

php - 通过 Laravel 中的 Controller 动态执行种子命令

php - 使用 Laravel 将项目 ID 附加到 slug 或通过 slug 在 MySQL 中查找

php - 在此服务器上找不到请求的 URL/practice/public/admin

javascript - Express.js 路由。如何将默认路由放在所有现有路由之前

php - 恢复解压 ('C*' , "string")

php - MySQL - 在 x 秒不活动后自动更新行(设置过期时间)

Php max_execution_time 被忽略

laravel - Laravel 项目中的“NotFoundHttpException”

node.js - 在 Express.js 中使用一个路由作为另一个路由的别名