Level.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. namespace App\Http\Controllers\admin;
  3. use App\Constants\HttpStatus;
  4. use App\Http\Controllers\Controller;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Validation\ValidationException;
  7. use Exception;
  8. use App\Models\Level as LevelModel;
  9. class Level extends Controller
  10. {
  11. /**
  12. * @api {get} /admin/level 会员等级列表
  13. *
  14. */
  15. function list()
  16. {
  17. try {
  18. $page = request()->input('page', 1);
  19. $limit = request()->input('limit', 15);
  20. $query = new LevelModel();
  21. $count = $query->count();
  22. $list = $query
  23. ->forPage($page, $limit)
  24. ->orderBy("level")
  25. ->get()->toArray();
  26. } catch (ValidationException $e) {
  27. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  28. } catch (Exception $e) {
  29. return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
  30. }
  31. return $this->success(['total' => $count, 'data' => $list]);
  32. }
  33. /**
  34. * @api {post} /admin/level/update 修改
  35. */
  36. public function update()
  37. {
  38. DB::beginTransaction();
  39. try {
  40. $params = request()->validate([
  41. 'id' => ['nullable'],
  42. 'level' => ['required'],
  43. 'level_name' => ['required'],
  44. 'img' => ['required'],
  45. 'recharge' => ['required'],
  46. ]);
  47. $id = $params['id'] ?? null;
  48. LevelModel::updateOrCreate(
  49. ['id' => $id],
  50. [
  51. 'level' => $params['level'],
  52. 'level_name' => $params['level_name'],
  53. 'img' => $params['img'],
  54. 'recharge' => $params['recharge'],
  55. ],
  56. );
  57. DB::commit();
  58. } catch (ValidationException $e) {
  59. DB::rollBack();
  60. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  61. } catch (Exception $e) {
  62. DB::rollBack();
  63. return $this->error(intval($e->getCode()), $e->getMessage());
  64. }
  65. return $this->success();
  66. }
  67. /**
  68. * @api {post} /admin/level/delete 删除
  69. */
  70. function delete()
  71. {
  72. DB::beginTransaction();
  73. try {
  74. request()->validate([
  75. 'id' => ['required', 'integer', 'min:1', 'max:99999999'],
  76. ]);
  77. $id = request()->input('id', 0);
  78. $info = LevelModel::where('id', $id)->first();
  79. if (!$info) throw new Exception("数据不存在", HttpStatus::CUSTOM_ERROR);
  80. $info->delete();
  81. DB::commit();
  82. } catch (ValidationException $e) {
  83. DB::rollBack();
  84. return $this->error(HttpStatus::VALIDATION_FAILED, $e->validator->errors()->first());
  85. } catch (Exception $e) {
  86. DB::rollBack();
  87. return $this->error(intval($e->getCode()));
  88. }
  89. return $this->success();
  90. }
  91. }