This is the 25th day of my participation in the August Genwen Challenge.More challenges in August

Add a category API

1. Classified management of migrating files

1.1 Create model and generate migration files

Run the commandphp artisan make:model Category -m:

1.2 Create table fields and perform migration files

Create the table fields in the migration file 2021_08_10_150705_create_categories_table.php:

public function up()
    {
        Schema::create('categories'.function (Blueprint $table) {
            $table->id();
            $table->string('name')->comment('Category name');
            $table->string('pid')->default(0)->comment('Parent, 0 superlative');
            $table->tinyInteger('status')->default(1)->comment('Status: 0 disabled, 1 enabled');
            $table->tinyInteger('level')->default(1)->comment('Classification level');
            $table->timestamps();
        });
    }
Copy the code


Run the commandphp artisan migrateTo migrate files:A classification table appears:

2. Classified management controller

Run the commandphp artisan make:controller Admin/CategoryController --api:Inherited base controller:


2.1 Method of Adding a Category Controller

Categorycontroller.php Add store as newsid

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'name'= >'required|max:16'
        ], [
            'name.required'= >'Category name cannot be empty'
        ]);

        Category::create($request->only(['name'.'pid']));
        return $this->response->created();
    }
Copy the code

A field validation that we’re writing directly into the controller. The second parameter allows you to customize the validation hint. $this->response->created(); Returns a success message.

2.2 Configuring the Model To allow adding fields

Add to Models\ category.php:

    // Field that can be batch assigned
    protected $fillable = ['name'.'pid'];
Copy the code

2.3 Adding Effects

2.4 Level Problems

We can see that there is a problem, that is, id 5 is a subclass of ID 1, so its level should be 2. So let’s deal with the categoryController.php controller logic:

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'name'= >'required|max:16'
        ], [
            'name.required'= >'Category name cannot be empty'
        ]);

        $pid = $request -> input('pid'.0);

        $insertData = [
            'name'= >$request -> input('name'),
            'pid'= >$pid.'level'= >$pid= =0 ? 1 : (Category::find($pid) -> level + 1)/ / calculate level
        ];

        Category::create($insertData);

        return $this->response->created();
    }
Copy the code

Because we addedlevelAnd so onModels\Category.phpAdd a batch assignment field to:

2.5 Test level issues

You can see that there are no problems now.

2.6 The maximum restriction level is 3

Again, handle the logic in the CategoryController.php controller:

    public function store(Request $request)
    {
        $request->validate([
            'name'= >'required|max:16'
        ], [
            'name.required'= >'Category name cannot be empty'
        ]);
        
        / / get the pid
        $pid = $request -> input('pid'.0);

        / / calculate level
        $level = $pid= =0 ? 1 : (Category::find($pid) -> level + 1); / / calculate level

        // Category does not exceed level 3
        if ($level > 3) return $this->response->errorBadRequest('Must not exceed grade 3 classification');

        $insertData = [
            'name'= >$request -> input('name'),
            'pid'= >$pid.'level'= >$level,]; Category::create($insertData);

        return $this->response->created();
    }
Copy the code

Effect:

3. Classify resource routes

Create a classified resource route in routes/admin.php:

// Manage resource routing by category
            $api->resource('category', CategoryController::class, [
                'except'= > ['destroy']]);Copy the code

We will exclude the deleted route, because the classification will later involve whether there is anything in this classification. If it is troublesome to delete, we will directly use enable and disable instead.

If you find this article helpful on your way to learning PHP, please follow me to like and comment on it. Thank you, your blog is definitely another support for me to write.