MenuPermission.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Eloquent\Factories\HasFactory;
  5. class MenuPermission extends Model
  6. {
  7. use HasFactory;
  8. protected $fillable = [
  9. 'user_id',
  10. 'menu_key',
  11. 'menu_label',
  12. 'menu_group',
  13. 'menu_url',
  14. 'is_visible',
  15. 'sort_order',
  16. 'additional_data',
  17. ];
  18. protected $casts = [
  19. 'is_visible' => 'boolean',
  20. 'sort_order' => 'integer',
  21. 'additional_data' => 'array',
  22. ];
  23. /**
  24. * 获取用户的菜单权限
  25. */
  26. public static function getUserMenus(string $userId, bool $onlyVisible = true)
  27. {
  28. $query = self::where('user_id', $userId);
  29. if ($onlyVisible) {
  30. $query->where('is_visible', true);
  31. }
  32. return $query->orderBy('sort_order')->get();
  33. }
  34. /**
  35. * 检查菜单是否可见
  36. */
  37. public static function isMenuVisible(string $userId, string $menuKey): bool
  38. {
  39. $permission = self::where('user_id', $userId)
  40. ->where('menu_key', $menuKey)
  41. ->first();
  42. return $permission ? $permission->is_visible : true; // 默认为可见
  43. }
  44. /**
  45. * 设置菜单可见性
  46. */
  47. public static function setMenuVisibility(string $userId, string $menuKey, bool $visible): void
  48. {
  49. self::updateOrCreate(
  50. [
  51. 'user_id' => $userId,
  52. 'menu_key' => $menuKey,
  53. ],
  54. [
  55. 'is_visible' => $visible,
  56. 'menu_label' => self::getDefaultMenuLabel($menuKey),
  57. ]
  58. );
  59. }
  60. /**
  61. * 获取默认菜单标签
  62. */
  63. private static function getDefaultMenuLabel(string $menuKey): string
  64. {
  65. $labels = [
  66. 'dashboard' => '仪表盘',
  67. 'exam-history' => '考试历史',
  68. 'exam-analysis' => '考试分析',
  69. 'ocr-paper-grading' => 'OCR试卷批改',
  70. 'intelligent-exam-generation' => '智能出卷',
  71. 'knowledge-graph' => '知识图谱',
  72. 'student-management' => '学生管理',
  73. 'teacher-management' => '老师管理',
  74. ];
  75. return $labels[$menuKey] ?? ucfirst($menuKey);
  76. }
  77. }