PHP code example of weijukeji / laravel-dictionary

1. Go to this page and download the library: Download weijukeji/laravel-dictionary library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

weijukeji / laravel-dictionary example snippets


return [
    // 数据库表名
    'table_categories' => 'dictionary_categories',
    'table_items' => 'dictionary_items',

    // API 路由配置
    'route_prefix' => 'api/dictionaries',
    'route_middleware' => ['api'],

    // 缓存配置
    'cache_enabled' => true,
    'cache_ttl' => 3600,
    'cache_prefix' => 'dict:',
    'cache_driver' => null,

    // 分页配置
    'per_page' => 15,
    'max_per_page' => 100,
];

// 前端传参
{
    "parent_key": "status",
    "item_value": "待处理",
    "auto_generate_key": true  // 自动生成键
}

// 后端自动生成规则:
// 1. 查找该分类下最大的纯数字键
// 2. 在最大值基础上 +1
// 3. 如果没有数字键,从 "1" 开始

use WeiJuKeJi\LaravelDictionary\Facades\Dict;

// 获取字典项
$items = Dict::getItemsByKey('status');

// 获取分类树
$tree = Dict::getTree();

use WeiJuKeJi\LaravelDictionary\Models\DictionaryCategory;
use WeiJuKeJi\LaravelDictionary\Models\DictionaryItem;

// 查询分类
$category = DictionaryCategory::where('category_key', 'status')->first();

// 查询字典项
$items = DictionaryItem::where('parent_key', 'status')
    ->enabled()
    ->orderBy('sort_order')
    ->get();

use WeiJuKeJi\LaravelDictionary\Services\DictionaryService;

$service = app(DictionaryService::class);

// 获取树形结构
$tree = $service->getTree();

// 保存分类
$category = $service->saveCategory([
    'category_key' => 'status',
    'category_name' => '状态分类',
    'sort_order' => 1
]);

// 保存字典项
$item = $service->saveItem([
    'parent_key' => 'status',
    'item_key' => '1',
    'item_value' => '启用',
    'sort_order' => 1,
    'is_enabled' => true
]);



namespace Database\Seeders;

use Illuminate\Database\Seeder;
use WeiJuKeJi\LaravelDictionary\Database\Seeders\DictionarySeeder;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        $this->call([
            DictionarySeeder::class,
            // 其他 Seeders...
        ]);
    }
}
bash
# 发布配置文件
php artisan vendor:publish --tag=dictionary-config

# 发布迁移文件
php artisan vendor:publish --tag=dictionary-migrations
bash
php artisan migrate
bash
# 导出到默认路径 database/seeders/dictionaries.json
php artisan dictionary:export

# 导出到指定路径
php artisan dictionary:export storage/app/dictionaries.json
bash
# 使用 Seeder 导入
php artisan db:seed --class=WeiJuKeJi\\LaravelDictionary\\Database\\Seeders\\DictionarySeeder

# 清空并重新导入(交互式确认)
php artisan dictionary:reseed

# 强制重新导入(不询问)
php artisan dictionary:reseed --force