按 id 或友好查询 URL - Laravel/Eloquent
Querying by id or friendly URL - Laravel/Eloquent
我正在与 laravel 一起开发 REST API。
我有一个博客table
Schema::create('blogs', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->longtext('body');
$table->string('friendly_url');
});
我为显示控制器设置了我的路线,它将显示按 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
得到相同的结果
我想知道这样做的最佳做法,有人可以帮忙吗?
我通常不喜欢使用具有相同 link 结构的 id 或 "slug"/"friendly url" 的想法,但你不能这样做吗:
$blog = Blog::where('id', $id)->orWhere('friendly_url', $id)->first();
我建议只使用友好 url。您拥有该字段是有原因的,尽管它在数据库中应该是唯一的。
我正在与 laravel 一起开发 REST API。
我有一个博客table
Schema::create('blogs', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->longtext('body');
$table->string('friendly_url');
});
我为显示控制器设置了我的路线,它将显示按 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
得到相同的结果
我想知道这样做的最佳做法,有人可以帮忙吗?
我通常不喜欢使用具有相同 link 结构的 id 或 "slug"/"friendly url" 的想法,但你不能这样做吗:
$blog = Blog::where('id', $id)->orWhere('friendly_url', $id)->first();
我建议只使用友好 url。您拥有该字段是有原因的,尽管它在数据库中应该是唯一的。