在我的家.blade中.php我有以下代码
<a href="{{ route('tasks.index') }}" class="btn btn-info">View Tasks</a>
<a href="{{ route('tasks.create') }}" class="btn btn-primary">Add New Task</a>
那么在路线上.php我有以下内容,
Route::get('/', [
'as' => 'home',
'uses' => 'PagesController@home'
]);
Route::get('/index', [
'as' => 'index',
'uses' => 'TasksController@index'
]);
Route::get('/create', [
'as' => 'create',
'uses' => 'TasksController@create'
]);
为什么我有这个错误 http://localhost:8000/
未定义路由 [任务.索引]。(查看: D:''wamp''www''test1''resources''views''pages''home.blade.php)
错误
未定义路由 [任务.索引]。(查看: D:''wamp''www''test1''resources''views''pages''home.blade.php)
这是因为您将其命名index
而不是tasks.index
,因此在路由声明中将名称从 index
更改为 task.index
,或者在 href
属性中引用路由时使用index
。现在你有这个:
Route::get('/index', [
'as' => 'index', // index is the name here so use the name as it is
'uses' => 'TasksController@index'
]);
与tasks.create
相同:
Route::get('/create', [
'as' => 'create', // Name is "create" not "tasks.create"
'uses' => 'TasksController@create'
]);
如果您使用一个组进行命名会更好,例如(对于 V-5.1 及更高版本):
Route::group(['as' => 'tasks.'], function () {
Route::get('/index', [
'as' => 'index', // Now you can usee 'tasks.index'
'uses' => 'TasksController@index'
]);
Route::get('/create', [
'as' => 'create', // Now you can usee 'tasks.create'
'uses' => 'TasksController@create'
]);
});
错误是因为 Laravel 找不到任何名为 tasks.index
或 tasks.create
的路由。这是因为您将路由命名为 index
和 create
和 home
。
因此,如果您希望链接指向URL:/tasks
,则必须使用其名称链接到该路由。
即:网址将被route('index')
。这是从路线中获取的:
从routes.php
文件中可以看到,'as'=>'index'
是路由的名称,这是您应该调用的名称。
所以链接变成:
<a href="{{ route('index') }}" class="btn btn-info">View Tasks</a>
<a href="{{ route('create') }}" class="btn btn-info">CreateTasks</a>
正如阿尔法所说,最好对路线进行分组。你也可以像这样链接方法
Route::group(['as' => 'tasks.'], function ()
{
Route::get('/index', 'TasksController@index')->name(index);
Route::get('/create', 'TasksController@create')->name(create);
});
定义路由后,您可以使用路由函数
{{ route('tasks.index') }}
{{ route('tasks.create') }}
或者,如果您不想对路由进行分组,可以这样做:
Route::get('/index', 'TasksController@index')->name(tasks.index);
Route::get('/create', 'TasksController@create')->name(tasks.create);
现在您可以使用:
<a href="{{ route('tasks.index') }}" class="btn btn-info">View Tasks</a>
<a href="{{ route('tasks.create') }}" class="btn btn-primary">Add New Task</a>
您可以在项目文件夹中查看运行以下命令的路由及其名称:
php artisan route:list