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 Stata 面板数据模型选择
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用