【问题标题】:Laravel 5.6 Resoure API route with slugLaravel 5.6 资源 API 路由与 slug
【发布时间】:2018-05-20 00:45:40
【问题描述】:

我在 Laravel 5.6 中安装了一个 json 端点,我希望使用 ID 以外的字段,例如 slug。 '/类别/我的蛞蝓'。默认使用 id 例如/类别/1

路线

Route::resource('categories', 'CategoryController')->middleware('cors');

类别控制器

public function show(Category $category)
{
    CategoryResource::withoutWrapping();
    return new CategoryResource($category);
}

分类资源

public function toArray($request)
{
    return [
        'type'          => 'categories',
        'id'            => (string)$this->id,
        'attributes'    => [
            'title' => $this->title,
            'description' => $this->description,
            'status' => $this->status,
            'slug' => $this->slug,
        ]
    ];
}

【问题讨论】:

  • 你正在尝试使用 laravel slug 辅助函数?我不确定你的问题

标签: php laravel-5.6


【解决方案1】:

在您的 Category 模型中添加:

public function getRouteKeyName()
{
    return 'slug';
}

这将使路由模型绑定与类别 slug 而不是 id 一起工作。你可以在这里阅读更多内容https://laravel.com/docs/5.6/routing#route-model-binding

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-24
    • 2018-09-26
    • 2018-09-28
    • 2011-03-30
    • 1970-01-01
    • 2014-10-23
    • 2019-07-10
    • 1970-01-01
    相关资源
    最近更新 更多