NormGroupService.php
1 <?php 2 3 namespace App\Http\Services; 4 5 use App\Http\Resources\NormGroupResource; 6 use App\Models\NormGroup; 7 use Exception; 8 9 class NormGroupService 10 { 11 /** 12 * Display a listing of the resource. 13 * 14 * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection 15 */ 16 public static function index($filters = null) 17 { 18 return NormGroup::when(isset($filters['search']), function ($query) use ($filters) { 19 $query->where('name', 'like', '%' . $filters['search'] . '%') 20 ->orWhere('description', 'like', '%' . $filters['search'] . '%'); 21 })->when(isset($filters['withTrashed']) && $filters['withTrashed'], fn($query) => $query->withTrashed()) 22 ->orderBy('name', 'asc') 23 ->paginate(10); 24 } 25 26 /** 27 * Create a resource 28 * 29 * @param array $data 30 * @return true 31 * @throws Exception 32 */ 33 public static function create(array $data): bool 34 { 35 if (NormGroup::create($data)) { 36 return true; 37 } else { 38 throw new Exception(__('norms.group.notifications.create.error.message')); 39 } 40 } 41 42 /** 43 * Destroy a resource 44 * 45 * @param int $normId 46 * @return true 47 * @throws Exception 48 */ 49 public static function remove(int $groupId): bool 50 { 51 if (NormGroup::destroy($groupId)) { 52 return true; 53 } else { 54 throw new Exception(__('norms.group.notifications.remove.error.message')); 55 } 56 } 57 58 /** 59 * Update a resource 60 * 61 * @param array $data 62 * @param int $entityId 63 * @return true 64 * @throws Exception 65 */ 66 public static function update(array $data, int $entityId): bool 67 { 68 try { 69 $normGroup = NormGroup::findOrFail($entityId); 70 $normGroup->update($data); 71 return true; 72 73 } catch (Exception $e) { 74 logger()->error($e->getMessage()); 75 throw new Exception(__('norms.group.notifications.create.error.message')); 76 } 77 } 78 79 /** 80 * Display a listing of the resource. 81 * 82 * @param int $normGroupId 83 * @return NormGroupResource 84 */ 85 public static function find(int $normGroupId) 86 { 87 return new NormGroupResource(NormGroup::where('id', $normGroupId)->first()); 88 } 89 90 public static function getNormGroups() 91 { 92 return NormGroup::query() 93 ->select('id', 'name') 94 ->orderBy('name') 95 ->get(); 96 } 97 98 public static function restore(int $entityId): bool 99 { 100 try { 101 $normGroup = NormGroup::withTrashed()->findOrFail($entityId); 102 $normGroup->restore(); 103 return true; 104 } catch (Exception $e) { 105 logger()->error($e->getMessage()); 106 throw new Exception(__('norms.group.notifications.restore.error.message')); 107 } 108 } 109 }