VueRouter.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App\Models;
  3. use App\Traits\ModelTree;
  4. use App\Utils\Admin;
  5. use Illuminate\Database\Eloquent\Builder;
  6. class VueRouter extends Model
  7. {
  8. use ModelTree {
  9. ModelTree::allNodesQuery as parentAllNodesQuery;
  10. }
  11. protected $casts = [
  12. 'parent_id' => 'integer',
  13. 'order' => 'integer',
  14. 'cache' => 'bool',
  15. 'menu' => 'bool',
  16. ];
  17. protected $fillable = [
  18. 'parent_id',
  19. 'order',
  20. 'title',
  21. 'icon',
  22. 'path',
  23. 'cache',
  24. 'menu',
  25. 'permission',
  26. ];
  27. protected $treeWithAuth = false;
  28. /**
  29. * parent_id 默认为 0 处理
  30. *
  31. * @param $value
  32. */
  33. public function setParentIdAttribute($value)
  34. {
  35. $this->attributes['parent_id'] = $value ?: 0;
  36. }
  37. public function roles()
  38. {
  39. return $this->belongsToMany(
  40. AdminRole::class,
  41. 'vue_router_role',
  42. 'vue_router_id',
  43. 'role_id'
  44. );
  45. }
  46. public function treeWithAuth()
  47. {
  48. $this->treeWithAuth = true;
  49. return $this;
  50. }
  51. protected function allNodesQuery(): Builder
  52. {
  53. return $this->parentAllNodesQuery()
  54. ->when($this->treeWithAuth, function (Builder $query) {
  55. $query->with('roles');
  56. });
  57. }
  58. protected function ignoreTreeNode($node): bool
  59. {
  60. // 不需要鉴权,或者有权限,则不忽略
  61. if (
  62. // 不需要鉴权
  63. !$this->treeWithAuth ||
  64. // 角色可见
  65. (Admin::user()->visible($node['roles']) &&
  66. // 并且路由没有配置权限,或者配置了权限,用户也有权限
  67. (empty($node['permission']) ?: Admin::user()->can($node['permission'])))
  68. ) {
  69. return false;
  70. } else {
  71. return true;
  72. }
  73. }
  74. }