PHPackages                             weijukeji/laravel-dictionary - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. weijukeji/laravel-dictionary

ActiveLibrary[Caching](/categories/caching)

weijukeji/laravel-dictionary
============================

Laravel Dictionary package for managing dictionary categories and items with caching support

v1.2.0(3mo ago)08↓33.3%MITPHPPHP ^8.2

Since Dec 17Pushed 3mo agoCompare

[ Source](https://github.com/WeiJuKeJi/laravel-dictionary)[ Packagist](https://packagist.org/packages/weijukeji/laravel-dictionary)[ RSS](/packages/weijukeji-laravel-dictionary/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (4)Versions (3)Used By (0)

Laravel Dictionary
==================

[](#laravel-dictionary)

[![Latest Version on Packagist](https://camo.githubusercontent.com/1e0dd678ff25618ff422be430a4e1d1b6ee22aff440db11fa0f7380a6916df38/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7765696a756b656a692f6c61726176656c2d64696374696f6e6172792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/weijukeji/laravel-dictionary)[![Total Downloads](https://camo.githubusercontent.com/e4b2bc911fde065b0afd03df624957296308774272b44f44fa6ce9e96c5eb428/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7765696a756b656a692f6c61726176656c2d64696374696f6e6172792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/weijukeji/laravel-dictionary)[![License](https://camo.githubusercontent.com/a2b6444a00c2979994be69e7bda753e6c81f5f5e9c414b54fcd1730308bcaf0a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f7765696a756b656a692f6c61726176656c2d64696374696f6e6172792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/weijukeji/laravel-dictionary)

一个功能完整、易于使用的 Laravel 字典管理包，支持分类和字典项的统一管理，内置缓存优化，提供 RESTful API 接口。

[English](README.md) | [简体中文](README_CN.md)

特性
--

[](#特性)

- ✨ **分类管理** - 支持字典分类的树形结构管理
- 📝 **字典项管理** - 灵活的字典项增删改查
- 🔢 **自动生成值** - 支持自动生成字典项数值
- ⚡ **高性能** - 内置缓存支持，优化查询性能
- 🔌 **即插即用** - 开箱即用的 API 接口
- 🎯 **RESTful 风格** - 标准的 RESTful API 设计
- 📦 **易于扩展** - 清晰的代码结构，方便二次开发
- 🔒 **数据过滤** - 集成 EloquentFilter 支持复杂查询
- 🌱 **数据导入导出** - 支持导出和导入种子数据
- 🗄️ **多数据库支持** - 支持 MySQL、PostgreSQL、SQLite 等

环境要求
----

[](#环境要求)

- PHP &gt;= 8.2
- Laravel &gt;= 11.0

安装
--

[](#安装)

通过 Composer 安装包：

```
composer require weijukeji/laravel-dictionary
```

发布配置文件和迁移文件：

```
# 发布配置文件
php artisan vendor:publish --tag=dictionary-config

# 发布迁移文件
php artisan vendor:publish --tag=dictionary-migrations
```

运行数据库迁移：

```
php artisan migrate
```

配置
--

[](#配置)

配置文件位于 `config/dictionary.php`：

```
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,
];
```

使用指南
----

[](#使用指南)

### API 端点

[](#api-端点)

包提供了完整的 RESTful API 接口：

#### 字典分类

[](#字典分类)

```
# 获取分类列表（分页）
GET /api/dictionaries/categories

# 获取分类树
GET /api/dictionaries/tree

# 创建分类
POST /api/dictionaries/categories

# 更新分类
PUT /api/dictionaries/categories/{id}

# 删除分类
DELETE /api/dictionaries/categories/{id}
```

#### 字典项

[](#字典项)

```
# 获取字典项列表（分页）
GET /api/dictionaries/items

# 根据分类键获取字典项
GET /api/dictionaries/items/by-key/{categoryKey}

# 创建字典项
POST /api/dictionaries/items

# 更新字典项
PUT /api/dictionaries/items/{id}

# 删除字典项
DELETE /api/dictionaries/items/{id}
```

### 请求示例

[](#请求示例)

#### 创建字典分类

[](#创建字典分类)

```
curl -X POST http://your-app.test/api/dictionaries/categories \
  -H "Content-Type: application/json" \
  -d '{
    "parent_id": null,
    "category_key": "status",
    "category_name": "状态分类",
    "sort_order": 1
  }'
```

#### 创建字典项（手动输入键）

[](#创建字典项手动输入键)

```
curl -X POST http://your-app.test/api/dictionaries/items \
  -H "Content-Type: application/json" \
  -d '{
    "parent_key": "status",
    "item_key": "1",
    "item_value": "启用",
    "sort_order": 1,
    "is_enabled": true,
    "auto_generate_key": false
  }'
```

#### 创建字典项（自动生成键）

[](#创建字典项自动生成键)

```
curl -X POST http://your-app.test/api/dictionaries/items \
  -H "Content-Type: application/json" \
  -d '{
    "parent_key": "status",
    "item_value": "停用",
    "sort_order": 2,
    "is_enabled": true,
    "auto_generate_key": true
  }'
```

#### 获取字典项

[](#获取字典项)

```
curl http://your-app.test/api/dictionaries/items/by-key/status
```

### 自动生成字典键

[](#自动生成字典键)

创建字典项时，可以选择自动生成数字键：

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

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

**生成示例：**

- 首次创建：生成 `"1"`
- 已有 `"1", "2", "3"`：生成 `"4"`
- 已有 `"1", "active", "99"`：生成 `"100"`（忽略非数字键）

### 在代码中使用

[](#在代码中使用)

#### 使用 Facade

[](#使用-facade)

```
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
]);
```

数据导入导出
------

[](#数据导入导出)

### 导出字典数据

[](#导出字典数据)

将当前数据库中的字典数据导出为 JSON 文件：

```
# 导出到默认路径 database/seeders/dictionaries.json
php artisan dictionary:export

# 导出到指定路径
php artisan dictionary:export storage/app/dictionaries.json
```

### 导入字典数据

[](#导入字典数据)

从 JSON 文件导入字典数据：

```
# 使用 Seeder 导入
php artisan db:seed --class=WeiJuKeJi\\LaravelDictionary\\Database\\Seeders\\DictionarySeeder

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

# 强制重新导入（不询问）
php artisan dictionary:reseed --force
```

### 在 DatabaseSeeder 中使用

[](#在-databaseseeder-中使用)

```
