laravel - Laravel 路由访问类别和显示方法
问题描述
要显示我使用以下路线的博客列表
// Blog List
Route::name('blog')->get('blog', 'Front\BlogController@index');
例如:http ://www.mypropstore.com/blog/
要显示博客类别,
Route::name('category')->get('blog/{category}', 'Front\PostController@category');
例如:http ://www.mypropstore.com/blog/buy-sell
为了显示博客详细信息、评论和标签详细信息,我们使用了“帖子”中间件
// Posts and comments
Route::prefix('posts')->namespace('Front')->group(function () {
Route::name('posts.display')->get('{slug}', 'PostController@show');
Route::name('posts.tag')->get('tag/{tag}', 'PostController@tag');
Route::name('posts.search')->get('', 'PostController@search');
Route::name('posts.comments.store')->post('{post}/comments', 'CommentController@store');
Route::name('posts.comments.comments.store')->post('{post}/comments/{comment}/comments', 'CommentController@store');
Route::name('posts.comments')->get('{post}/comments/{page}', 'CommentController@comments');
});
例如:http ://www.mypropstore.com/posts/apartment-vs-villa-which-is-the-right-choice-for-you
现在我想将博客详细信息 url 页面更改为
http://www.mypropstore.com/blog/apartment-vs-villa-which-is-the-right-choice-for-you- {{blogid}}
例如:http ://www.mypropstore.com/blog/apartment-vs-villa-which-is-the-right-choice-for-you-54
如果我更改上述格式,则会与类别页面冲突。任何人都知道如何设置博客详细信息页面的路由(中间件“帖子”)
解决方案
假设blogid
部分,在您建议的路线结束时......
http://www.mypropstore.com/blog/apartment-vs-villa-which-is-the-right-choice-for-you-{{blogid}}
...是数字,你可以这样做:
对于您的帖子详细信息页面的路由定义,请使用以下内容:
Route::name('posts.display')
->get('blog/{slug}-{id}', 'PostController@show')
->where('id', '[0-9]+');
这样做是为了确保该路由仅与遵循该模式的路径匹配,blog/{slug}-{id}
但限制id
您的路由部分必须是数字,即仅包含一个或多个数字。
您需要确保该路线出现在与您的路线匹配的category
路线之前,否则该category
路线将优先。
你的控制器应该有这样的 show 方法:
class PostController extends Controller
{
public function show($slug, $id)
{
// $id will contain the number at the end of the route
// $slug will contain the slug before the number (without the hyphen)
// You should be able to do this to get your post.
$post = Post::findOrFail($id);
dd($post);
}
}
推荐阅读
- c++ - 为什么我的链接列表中的数据在嵌套函数中发生更改/损坏?
- mysql - 尝试从同一个表中引用两个主键时如何修复外键约束?
- wcf - WCF 使用 HTTP 400 响应来自 Razor Pages 应用程序的序列化 JSON 字符串
- sql - 缩短查询
- c# - 在 LINQ 中执行 LEFT JOIN 后如何返回 NULL 值?
- reproducible-research - 我要对 facebook 评论进行情绪分析研究。知道如何为我的研究冷却 facebook 评论吗?
- php - Laravel 问题显示在 localhost 服务器上运行时添加了不必要的字符 运行时总是出现 f 字符
- javascript - 在 Electron 渲染器进程中持久化 nedb 到磁盘(Webpack/Electron/nedb 配置问题)
- node.js - 我正在使用 Nodemailer (Node js) 通过 Gmail 发送电子邮件,但出现错误
- java - 如何使用 ExpandableTextView 库从 Firebase 检索文本?