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

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

Link: [https://github.com/ndrto/laravel-romen](https://github.com/ndrto/laravel-romen)

C:\xampp82\htdocs\lva1\database\migrations\2023\_09\_16\_031931\_create\_menus\_table.php

```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
<?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
<?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
<?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');
  }
}

```

<figure><img src="https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2FDVmyKVemyTOCUbGYNXG4%2Fimage.png?alt=media&#x26;token=c3182721-57ee-4fa8-bd5e-f967c04cc9ab" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2FLgHjxk0zd2yrwtACJ8Lc%2Fimage.png?alt=media&#x26;token=0ac6384e-a8f9-4569-a566-f11d873a4801" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2F2vSmpdKpbAiSoPIjbSku%2Fimage.png?alt=media&#x26;token=b0ce8607-c730-4690-96b5-2599ff94ee5a" alt=""><figcaption></figcaption></figure>

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

```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

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

```

<figure><img src="https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2FZmSoN1DCdOThCkzaF4qI%2Fimage.png?alt=media&#x26;token=a3e64880-93f1-48de-b0ec-c2f4b557d63c" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2FoLYHqZY3jOjy90PAg0mj%2Fimage.png?alt=media&#x26;token=cbbdd25c-75e1-4971-b65e-ad36f6728ba2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2FLDA3jhnUcXe9YE3XFbcj%2Fimage.png?alt=media&#x26;token=6a3b6ef6-b943-4db6-8ca2-6d29edd131f7" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2Fjzt8PuN2DHSr4RftWiLK%2Fimage.png?alt=media&#x26;token=16e5b2c6-7e8a-45b7-94b0-7f781f35d5bd" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2F4d1X8zaNtZ7tin7wXOKx%2Fimage.png?alt=media&#x26;token=1b3c0b7f-7e84-436c-a70a-e18ede556ae2" alt=""><figcaption></figcaption></figure>



{% file src="https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2FjmeIBoI7b1XluUprLq3v%2Flva1-2.zip?alt=media&token=4bd8b741-9886-4074-8811-cbe096865ced" %}
