فهرست منبع

feat: adiciona unit em detalhes de usuario

ebagabee 2 هفته پیش
والد
کامیت
8223685eb7
2فایلهای تغییر یافته به همراه9 افزوده شده و 3 حذف شده
  1. 1 0
      app/Http/Resources/UserResource.php
  2. 8 3
      app/Services/UserService.php

+ 1 - 0
app/Http/Resources/UserResource.php

@@ -21,6 +21,7 @@ public function toArray(Request $request): array
             'user_type'     => $this->user_type,
             'status'        => $this->status,
             'state_id'      => $this->state_id,
+            'unit_id'       => $this->whenLoaded('units', fn() => $this->units->first()?->id),
             'avatar_url'    => $this->avatar_url
                 ? Storage::temporaryUrl($this->avatar_url, now()->addHours(24))
                 : null,

+ 8 - 3
app/Services/UserService.php

@@ -20,12 +20,12 @@ public function authUser(): ?User
 
     public function getAll(): Collection
     {
-        return User::with('state')->orderBy('name')->get();
+        return User::with(['state', 'units'])->orderBy('name')->get();
     }
 
     public function findById(int $id): ?User
     {
-        return User::with('state')->find($id);
+        return User::with(['state', 'units'])->find($id);
     }
 
     public function create(array $data): User
@@ -54,10 +54,15 @@ public function update(int $id, array $data): ?User
             return null;
         }
 
+        $unitId = $data['unit_id'] ?? null;
         unset($data['unit_id']);
+
         $data = $this->handleAvatar($data, $model->avatar_url);
         $model->update($data);
-        return $model->fresh(['state']);
+
+        $model->units()->sync($unitId ? [$unitId] : []);
+
+        return $model->fresh(['state', 'units']);
     }
 
     public function delete(int $id): bool