我正在和laravel一起开发REST API。
我有一张博客桌
Schema::create('blogs', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->longtext('body');
$table->string('friendly_url');
});
我已经为show控制器设置了我的路线,它将显示通过id搜索的博客。
路由
Route::get('/{id}', 'BlogController@show');
控制器
public function show($id)
{
$blog = Blog::find($id);
if (!$blog) {
return response()->json([
'message' => '404 Not Found'
], 400);
}
return response()->json($blog, 200);
}
因此,通过访问
/api/blog/1
我得到了
{
"id": 1,
"title": "title of my blog",
"body": "conteudo do meu blog",
"friendly_url": "title-of-my-blog",
"category_id": 2
}
但是我也想通过友好的URL来查看博客
/api/blog/{friendly-url} OR {id}
/api/blog/title-of-my-blog
并得到相同的结果
我想知道做这件事的最佳实践,有人来帮忙吗?
发布于 2018-09-06 14:21:41
我通常不喜欢使用id或具有相同链接结构的"slug"/"friendly url“的想法,但你就不能这样做:
$blog = Blog::where('id', $id)->orWhere('friendly_url', $id)->first();
我推荐使用友好的url。您拥有该字段是有原因的,尽管它在数据库中应该是唯一的。
https://stackoverflow.com/questions/52206066
复制