Permission.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Builder;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Database\Eloquent\Relations\BelongsToMany;
  6. use Illuminate\Support\Collection;
  7. class Permission extends Model
  8. {
  9. public const TYPE_ACTION = 'action';
  10. public const TYPE_FIELD = 'field';
  11. protected $fillable = [
  12. 'slug',
  13. 'name',
  14. 'description',
  15. 'module',
  16. 'entity',
  17. 'field',
  18. 'action',
  19. 'type',
  20. 'group',
  21. 'sort',
  22. 'is_system',
  23. ];
  24. protected function casts(): array
  25. {
  26. return [
  27. 'is_system' => 'boolean',
  28. ];
  29. }
  30. public function roles(): BelongsToMany
  31. {
  32. return $this->belongsToMany(Role::class, 'role_permissions')
  33. ->withPivot('effect')
  34. ->withTimestamps();
  35. }
  36. public function users(): BelongsToMany
  37. {
  38. return $this->belongsToMany(User::class, 'user_permissions')
  39. ->withPivot(['effect', 'reason', 'expires_at'])
  40. ->withTimestamps();
  41. }
  42. public function scopeActionPermissions(Builder $query): Builder
  43. {
  44. return $query->where('type', self::TYPE_ACTION);
  45. }
  46. public function scopeFieldPermissions(Builder $query): Builder
  47. {
  48. return $query->where('type', self::TYPE_FIELD);
  49. }
  50. public static function getGroupedForUi(): Collection
  51. {
  52. return self::query()
  53. ->orderBy('sort')
  54. ->orderBy('module')
  55. ->orderBy('type')
  56. ->orderBy('slug')
  57. ->get()
  58. ->groupBy('group');
  59. }
  60. }