CityService.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace App\Services;
  3. use App\Models\City;
  4. use App\Models\State;
  5. use Illuminate\Database\Eloquent\Collection;
  6. class CityService
  7. {
  8. public function getAll(): Collection
  9. {
  10. return City::query()->orderBy('name', 'asc')->get();
  11. }
  12. public function findById(int $id): ?City
  13. {
  14. return City::find($id);
  15. }
  16. public function create(array $data): City
  17. {
  18. return City::create($data);
  19. }
  20. public function update(int $id, array $data): ?City
  21. {
  22. $model = $this->findById($id);
  23. if (! $model) {
  24. return null;
  25. }
  26. $model->update($data);
  27. return $model->fresh();
  28. }
  29. public function delete(int $id): bool
  30. {
  31. $model = $this->findById($id);
  32. if (! $model) {
  33. return false;
  34. }
  35. return $model->delete();
  36. }
  37. public function findStateCityByDescription(string $state, string $city): ?array
  38. {
  39. $state = State::query()
  40. ->where('code', $state)
  41. ->select(
  42. 'name as label',
  43. 'id as value',
  44. )
  45. ->first();
  46. $city = City::query()
  47. ->where('state_id', $state->value)
  48. ->where('name', $city)
  49. ->select(
  50. 'name as label',
  51. 'id as value',
  52. 'state_id',
  53. )
  54. ->first();
  55. return [
  56. 'state' => $state,
  57. 'city' => $city,
  58. ];
  59. }
  60. }