Laravel 中命名路由的一些用例是什么?

What are some use cases of Named Routes in Laravel?

读完documentation后,我对Laravel中的Named Routes是什么还是一知半解。

你能帮我理解一下吗?

Route::get('user/profile', function () {
    //
})->name('profile');
Route::get('user/profile', 'UserProfileController@show')->name('profile');

它说:

Once you have assigned a name to a given route, you may use the route's name when generating URLs or redirects via the global route function

我不明白这句话的第二部分是什么意思,关于生成 URL 或重定向。

在上述示例中 profile 的情况下,生成的 URL 会是什么?我将如何使用它?

为路由添加名称后,您可以使用 route() 助手创建 urls。 现在可以在您的应用程序中使用它了。

例如,在您的 blade 模板中,这可能如下所示:

{{ route('profile') }}

这将使用应用程序 url 和路由路径创建一个 url。

这是它的样子:

命名路由样本name('store');:

Route::get('/store-record','YourController@function')->name('store');

store 是这里的命名路由。调用它使用 route('store')

正在定义另一种类型的路线。这不是命名路线:

Route::get('/store-record','YourController@function')

您可以使用 {{ url('/store-record') }}

访问此路线

希望这对您有所帮助

最好的资源就在这里:https://laravel.com/docs/5.8/routing#named-routes

您认为其中一个常见用例。假设您的 post 请求转到特定路线,基本上没有命名路线,您可以像这样简单地存储任务

action="/task"

但是比如说你需要将路线更新为 /task/store ,你将需要在你使用路线的任何地方更新它。

但考虑到您使用了命名路由

Route::post('/task', 'TaskController@store')->name('task.store'); 

通过命名路由,您可以在您的视图中使用这样的路由:

action="{{route('task.store')}}"

现在如果您选择更新您的路线,您只需要在路线文件中进行更改并将其更新为您需要的任何内容。

Route::post('/task/now/go/here', 'TaskController@store')->name('task.store');

如果你需要将参数传递给你的路由,你可以像这样将它作为参数传递给路由助手:

route('task.edit', 1), // in resource specific example it will output /task/1/edit 

所有视图示例都是使用 blade 模板提供的。