CityService.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. }