## dcat-admin 菜单或权限幂等可重复执行数据迁移
同理,laravel-admin应该也可同等操作,在laravel项目中 database/seeders 目录下创建对应php数据填充文件
- 菜单操作
``` php
<?php
namespace Database\Seeders;
use Encore\Admin\Auth\Database\Menu;
use Illuminate\Database\Seeder;
class AdminMenuSeeder extends Seeder
{
/**
* 创建菜单,子菜单。根据 title 和 uri 判断是否已经存在
* @return void
*/
private function createMenu($item)
{
$children = false;
$where = ['title' => $item['title'], 'uri' => $item['uri']];
isset($item['children']) && $children = $item['children'];
unset($item['children']);
$menu = Menu::query()->firstOrCreate($where, $item);
if ($children) {
foreach ($children as $child) {
$child['parent_id'] = $menu->id;
$this->createMenu($child);
}
}
}
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$data = [
[
'title' => '会员列表', 'icon' => 'fa-group', 'uri' => '/user',
'children' => [
['title' => '会员管理', 'icon' => 'fa-bars', 'uri' => '/user'],
['title' => '会员等级管理', 'icon' => 'fa-user-secret', 'uri' => '/users_level'],
],
],
[
'title' => '内容管理', 'icon' => 'fa-bars', 'uri' => null,
'children' => [
['title' => '栏目管理', 'icon' => 'fa-bars', 'uri' => '/category'],
['title' => '文章管理', 'icon' => 'fa-bars', 'uri' => '/article'],
['title' => '版权管理', 'icon' => 'fa-copyright', 'uri' => '/copyright'],
],
]
];
foreach ($data as $item) {
$this->createMenu($item);
}
}
}
```
- 权限操作
``` php
<?php
namespace Database\Seeders;
use App\Common\Models\AdminPermissions;
use Illuminate\Database\Seeder;
class PermissionsSeeder extends Seeder
{
/**
*
* @return void
*/
private function create($item)
{
$where = ["name" => $item["name"], "slug" => $item["slug"], "http_method" => $item["http_method"], "http_path" => $item["http_path"]];
$query = AdminPermissions::query();
$query->upsert($where, ["name"], ["slug", "http_method", "http_path"]);
}
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$data = [
//首页
["name" => "首页", "slug" => "index", "http_method" => "", "http_path" => "/"]
];
foreach ($data as $item) {
$this->create($item);
}
}
}
```
添加 AdminMenuSeeder和PermissionsSeeder 到 DatabaseSeeder
``` php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
$this->call(AdminMenu::class);
$this->call(PermissionsSeeder::class);
}
}
```
- 执行
``` Bash
# 执行命令即可
php artisan db:seed DatabaseSeeder
# 或者单独执行
php artisan db:seed AdminMenuSeeder
```