帮我用laravel来写一个添加无限极分类的接口
时间: 2023-02-27 19:17:14 浏览: 65
好的,我可以为您提供一份代码示例。首先,您需要先创建一个模型,用来存储分类信息,例如:
```
php artisan make:model Category -m
```
接着,在数据表中添加 parent_id 字段,以存储分类的父子关系,在数据库迁移文件中添加以下代码:
```
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->unsignedBigInteger('parent_id')->nullable();
$table->timestamps();
});
```
最后,您可以创建一个控制器,用来处理添加分类的请求:
```
php artisan make:controller CategoryController
```
在控制器中,您可以添加一个 store 方法,用来处理添加分类的请求:
```
public function store(Request $request)
{
$category = new Category;
$category->name = $request->name;
$category->parent_id = $request->parent_id;
$category->save();
return response()->json([
'message' => 'Category added successfully.',
'category' => $category
], 201);
}
```
该代码将会创建一个新的分类,并将其存储到数据库中。返回的响应是一个 JSON 对象,其中包含了添加成功的消息和刚刚添加的分类对象。
希望这些代码对您有所帮助!