Laravel Backpack CRUD for categories

Rate this post

This is part 4 of the series seo site manager in Laravel.

1. Create the migration file for category

php artisan make:migration create_categories_table –table=categories

    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            //
            $table->id();
            $table->string('name');
            $table->string('slug', 150)->unique()->nullable();
            $table->timestamps();
        });
    }

Optional If you want to reorder & nest categories, you have to add Reorder Operation.

Reorder operation

Your model should have the following integer fields, with a default value of 0: parent_id, lft, rgt, depth.
Additionally, the parent_id field has to be nullable.

So add the following fields to the migration file:

    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            //
            $table->id();
            $table->string('name');
            $table->string('slug', 150)->unique()->nullable();   
            $table->integer('parent_id')->default(0)->nullable();
            $table->integer('lft')->default(0); 
            $table->integer('rgt')->default(0);  
            $table->integer('depth')->default(0);     
            $table->timestamps();
        });
    }

2. Run the migration

php artisan migrate

3. Generate all files for Category Backpack\CRUD interface

php artisan backpack:crud Category

# Use singular, either PascalCase, snake_case, or kebab-case.

After you run the command, the following will be created:

Controller created successfully.
Model created successfully.
Request created successfully.
Successfully added code to routes/backpack/custom.php
Successfully added code to sidebar_content file.

4. Enable Reorder operation in CategoryCrudController

In order to Reorderthis operation in CategoryCrudController, have to use the ReorderOperation trait, and have a setupReorderOperation() method that defines the label and max_level of allowed depth.

So add the code below in CategoryCrudController:

/**
 * Class CategoryCrudController
 * @package App\Http\Controllers\Admin
 * @property-read \Backpack\CRUD\app\Library\CrudPanel\CrudPanel $crud
 */
class CategoryCrudController extends CrudController
{
...
    use \Backpack\CRUD\app\Http\Controllers\Operations\ReorderOperation;

...
    protected function setupReorderOperation()
    {
        // define which model attribute will be shown on draggable elements 
        $this->crud->set('reorder.label', 'name');
        // define how deep the admin is allowed to nest the items
        // for infinite levels, set it to 0
        $this->crud->set('reorder.max_level', 2);
    }

Read more here about reorder operation in backpack

5. Show ordered categories in the listing in admin

To see the ordered categories in the listing in admin you must add the following code in the setup() function:

$this->crud->orderBy('lft', 'asc'); 

6. Sets the columns that appear in the category listing

Columns help you specify which attributes are shown in the table and in which order.

CRUD::setFromDb(); // show all columns corresponding to all fields in the database 

/**
* Columns can be defined using the fluent syntax or array syntax:
* - CRUD::column('price')->type('number');
* - CRUD::addColumn(['name' => 'price', 'type' => 'number']); 
*/

7. Set the fields for Create and Update operation

Inside your Controller’s setupCreateOperation() or setupUpdateOperation() method, you’ll be able to define what fields you want the admin to see, when creating/updating entries. Read more here about getting started crud operations

protected function setupCreateOperation()
{
   CRUD::setValidation(CategoryRequest::class);
   //CRUD::setFromDb(); // show all fields from db

   CRUD::field('name')->type('text');
  /**
   * Fields can be defined using the fluent syntax or array syntax:
   * - CRUD::field('price')->type('number');
   * - CRUD::addField(['name' => 'price', 'type' => 'number'])); 
  */
 }

9. Set the validation rules that apply to the request

In CategoryRequest You can set rules that apply to the request.

    public function rules()
    {
        return [
            'name' => 'required|min:2|max:60'
        ];
    }

A red asterisk will appear next to the name field.

If your Update operation requires a different validation than the Create operation, You have to:

  • Create a separate request file for each operation;
  • Instruct your EntityCrudController to use separate files, in the “use” section;

For example, to create UpdateTagRequest.php and CreateTagRequest.php, with different validations, then in TagCrudController just do:

- use App\Http\Requests\TagRequest as StoreRequest;
+ use App\Http\Requests\CreateTagRequest as StoreRequest;
- use App\Http\Requests\TagRequest as UpdateRequest;
+ use App\Http\Requests\UpdateTagRequest as UpdateRequest;

10. Guard your model attributes!

Guard your model attributes! Only these you define in $fillable will be updated in the database, except for id, updated_at, created_at.

protected $fillable = ['name','slug'];

11. Create the slug for category name

In the Category model add:

use Illuminate\Support\Str;
...
class Category extends Model
{
...
/*
 |--------------------------------------------------------------------------
 | MUTATORS
|--------------------------------------------------------------------------
 */
 public function setNameAttribute($value)
 {
    $this->attributes['name'] = ucfirst($value);
    $this->attributes['slug'] = \Str::slug($value, '-');
 }
}

Also, the backpack uses Controller, so you can overwrite also the Controller’s store method if you want to add the slug in it.

11. Test the CRUD operations

Finally, I added some test categories and Created, Edit and Delete some records. I also tested the “Reorder categories” tab! Everything went well!

Hello there!

I hope you find this post useful!

I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.

If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!

subscribe youtube

Leave a Comment

WebPedia.net