😅Create database using json file,Tạo database menu file json permission, role (ok)

https://spatie.be/docs/menu/v3/introduction

Link: https://github.com/ndrto/laravel-romen

C:\xampp82\htdocs\lva1\database\migrations\2023_09_16_031931_create_menus_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
    Schema::create('menus', function (Blueprint $table) {
      $table->bigIncrements('id');
      $table->unsignedBigInteger('parent')->default(0)->index();
      $table->string('name')->unique();
      $table->string('title');
      $table->string('url')->index();
      $table->string('icon')->nullable();
      $table->string('class_icon')->nullable();
      $table->integer('order')->default(0)->index();
      $table->timestamps();
    });
    Schema::create('menu_role', function (Blueprint $table) {
      // $table->primary(['menu_id', 'role_id']);
      $table->unsignedBigInteger('menu_id');
      $table->unsignedBigInteger('role_id');
      // $table->foreign('menu_id')
      //   ->references('id')
      //   ->on('menus')
      //   ->cascadeOnUpdate()
      //   ->cascadeOnDelete();
      // $table->foreign('role_id')
      //   ->references('id')
      //   ->on('roles')
      //   ->cascadeOnUpdate()
      //   ->cascadeOnDelete();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    Schema::dropIfExists('menus');
    Schema::dropIfExists('menu_role');
  }
};

C:\xampp82\htdocs\lva1\database\seeders\HasJsonFile.php

<?php
namespace Database\Seeders;
use File;
use InvalidArgumentException;
trait HasJsonFile
{
  public function getJson($associative = false)
  {
    return json_decode(File::get($this->jsonFile()), $associative);
  }
  protected function jsonFile(): string
  {
    return '';
  }
}

C:\xampp82\htdocs\lva1\database\seeders\MenuSeeder.php

<?php
namespace Database\Seeders;
use Ndrto\Romen\Models\Menu;
use Arr;
use Artisan;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
class MenuSeeder extends Seeder
{
  use HasJsonFile;
  public function run()
  {
    $this->registerMenus($this->getJson(true), 0);
    Artisan::call('cache:clear');
  }
  protected function jsonFile(): string
  {
    return database_path('seeders/data/menus.json');
  }
  public function registerMenus($menus, $parent = 0)
  {
    if (empty($menus)) {
      return;
    }
    foreach ($menus as $menu) {
      // register menu
      $created = Menu::updateOrCreate(
        ['name' => Arr::get($menu, 'name')],
        [
          'parent' => $parent,
          'title' => Arr::get($menu, 'title'),
          'url' => Arr::get($menu, 'url'),
          'order' => Arr::get($menu, 'order', 0),
          'class_icon' => Arr::get($menu, 'icon'),
        ]
      );
      // assign menu with role
      $roles = $this->extractRoleIds(Arr::get($menu, 'roles'));
      // assign roles to menu
      $created->roles()->sync($roles);
      // register child menu
      $this->registerMenus(Arr::get($menu, 'child'), $created->id);
    }
  }
  protected function extractRoleIds($roles)
  {
    if ($roles == '*') {
      return Role::get()->pluck('id')->toArray();
    }
    return Role::whereIn('name', $roles)->pluck('id')->toArray();
  }
}

C:\xampp82\htdocs\lva1\database\seeders\RoleSeeder.php

<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
class RoleSeeder extends Seeder
{
  use HasJsonFile;
  public function run()
  {
    foreach ($this->getJson(true) as $data) {
      $role = Role::updateOrCreate(
        ['name' => $data['role']]
      );
      $this->assignPermissions($role, $data['permissions']);
    }
  }
  protected function assignPermissions($role, array $permissions)
  {
    $this->createPermissions($permissions);
    $role->syncPermissions($permissions);
  }
  protected function createPermissions(array $permissions)
  {
    foreach ($permissions as $permission) {
      Permission::updateOrCreate(
        ['name' => $permission]
      );
    }
  }
  protected function jsonFile(): string
  {
    return database_path('seeders/data/roles.json');
  }
}

C:\xampp82\htdocs\lva1\database\seeders\data\menus.json

[
  {
    "name": "home",
    "title": "Home",
    "url": "/admin/home",
    "order": "1",
    "icon": "os-icon os-icon-window-content",
    "roles": ["administrator", "operator"],
    "child": []
  },
  {
    "name": "logout",
    "title": "Logout",
    "url": "/logout",
    "order": "9",
    "icon": "os-icon os-icon-signs-11",
    "roles": "*",
    "child": []
  }
]

C:\xampp82\htdocs\lva1\database\seeders\data\roles.json

[
  {
    "role": "administrator",
    "permissions": [
      "create-project",
      "edit-project",
      "delete-project",
      "view-project"
    ]
  },
  {
    "role": "operator",
    "permissions": ["view-project"]
  }
]

Last updated