Laravel 5.6 Resoure API路线与slug

时间:2018-05-20 00:45:40

标签: php laravel-5.6

我在Laravel 5.6中安装了一个json端点,我希望使用ID之外的字段,例如slug,例如“/类别/我的段塞”。默认值使用id,例如/类别/ 1

路线

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

CategoryController

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,
        ]
    ];
}

1 个答案:

答案 0 :(得分:1)

类别模型中添加以下内容:

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

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