AddressService.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace App\Modules\Mini\Services;
  3. use App\Base\BaseService;
  4. use App\Models\User\User;
  5. use App\Models\User\UserAddress;
  6. class AddressService extends BaseService
  7. {
  8. public function store(User $user, $params)
  9. {
  10. $id = $params['id'];
  11. if ($id) {
  12. $address = UserAddress::where("id", $id)->where("user_id", $user->id)->firstOrFail();
  13. } else {
  14. $address = new UserAddress();
  15. $address->user_id = $user->id;
  16. }
  17. $address->address = $params['address'];
  18. $address->name = $params['name'];
  19. $address->phone = $params['phone'];
  20. $address->is_default = (int)$params['is_default'];
  21. if (UserAddress::where("user_id", $user->id)->count() == 0) {
  22. $address->is_default = 1;
  23. }
  24. $address->area = $params['area'];
  25. $address->save();
  26. if ($address->is_default == 1) {
  27. UserAddress::where("user_id", $user->id)->where("id", "<>", $address->id)->update([
  28. "is_default" => 0,
  29. ]);
  30. }
  31. }
  32. public function paginate(User $user, $params)
  33. {
  34. $p = UserAddress::where("user_id", $user->id)->orderByDesc("id")->paginate($params['page_size']);
  35. return [
  36. "total" => $p->total(),
  37. "page_total" => $p->lastPage(),
  38. "list" => array_map(function (UserAddress $model) {
  39. return [
  40. "id" => $model->id,
  41. "is_default" => $model->is_default,
  42. "name" => $model->name,
  43. "phone" => $model->phone,
  44. "area" => $model->area,
  45. "address" => $model->address,
  46. ];
  47. }, $p->items()),
  48. ];
  49. }
  50. }