通过id或友好URL查询 - Laravel / Eloquent

问题描述 投票:0回答:1

我正在使用laravel开发REST API。

我有一个博客表

Schema::create('blogs', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->longtext('body');
    $table->string('friendly_url');
});

我有一个为show controller设置的路由,它将显示由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

并得到相同的结果

我想知道做这件事的最佳做法,有人帮忙吗?

php laravel api eloquent laravel-5.6
1个回答
1
投票

我通常不喜欢使用相同链接结构的id或“slug”/“友好网址”的想法,但你不能这样做:

$blog = Blog::where('id', $id)->orWhere('friendly_url', $id)->first();

我建议只使用友好的网址。您有该字段是有原因的,尽管它在数据库中应该是唯一的。

© www.soinside.com 2019 - 2024. All rights reserved.