drcmg28484 2018-09-06 14:12
浏览 82
已采纳

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

I'm working on a REST API with laravel.

I have a blogs table

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

I have a my route set up for the show controller that will display the blog searched by id

Route

Route::get('/{id}', 'BlogController@show');

Controller

public function show($id)
{
    $blog = Blog::find($id);
        if (!$blog) {
            return response()->json([
                'message' => '404 Not Found'
            ], 400);
        }
    return response()->json($blog, 200);
}

So by accessing

/api/blog/1

I get

{
    "id": 1,
    "title": "title of my blog",
    "body": "conteudo do meu blog",
    "friendly_url": "title-of-my-blog",
    "category_id": 2
}

but I want to check the blog also by the friendly URL

/api/blog/{friendly-url} OR {id}

/api/blog/title-of-my-blog

and get the same result

I would like to know the best practice to do this, someone to help?

  • 写回答

1条回答 默认 最新

  • douhai5835 2018-09-06 14:21
    关注

    I don't usually like the idea of using the id or the "slug"/"friendly url" with the same link structure but can't you just do:

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

    I'd recommend just using the friendly url. You have that field for a reason, although it should be unique in the database.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记