Laravel 5.6 Resoure API route with slug



我在Laravel 5.6中安装了一个json端点,我希望使用ID以外的字段,例如slug,例如'/categories/my-slug'。默认使用 id,例如/categories/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,
]
];
}

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

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

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

最新更新