Laravel URL 处理:路由命名生成 URL
问题
如何获取命名路由的 URL?
回答
全局辅助函数 route
可以用于生成(获取)命名路由的 URL,假设有如下路由:
Route::get('/post/{post}', function () {
//
})->name('post.show');
要生成此路由的 URL,可以使用 route
函数:
echo route('post.show', ['post' => 1]);
// http://example.com/post/1
也可以将 Eloquent 模型作为参数值传递,route
函数将自动提取模型的主键:
echo route('post.show', ['post' => $post]);
辅助函数 route
还可用于为具有多个参数的路由生成 URL:
Route::get('/post/{post}/comment/{comment}', function () {
//
})->name('comment.show');
echo route('comment.show', ['post' => 1, 'comment' => 3]);
// http://example.com/post/1/comment/3
推荐文章: