海南旅游SAAS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
1.9 KiB

  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\AgentProduct;
  5. use App\Models\UserFav;
  6. use Illuminate\Support\Facades\Storage;
  7. /**
  8. * 用户收藏
  9. * Class UserFavController
  10. * @package App\Http\Controllers\Api
  11. */
  12. class UserFavController extends Controller
  13. {
  14. public function index()
  15. {
  16. $list = UserFav::query()
  17. ->with([
  18. 'agentProduct:id,price,original_price',
  19. 'product:id,title,pictures',
  20. ])
  21. ->where('user_id', $this->user_id)
  22. ->select('id', 'agent_product_id', 'product_id', 'created_at')
  23. ->orderBy('id', 'DESC')
  24. ->simplePaginate(15);
  25. if (!$list->isEmpty()) {
  26. $list = $list->toArray();
  27. $prefix = Storage::disk('public')->url('');
  28. if ($list['data']) {
  29. foreach ($list['data'] as &$v) {
  30. if (!empty($v['product']['pictures'])) {
  31. //单图
  32. if (strpos($v['product']['picture'], $prefix) === false) {
  33. $v['product']['picture'] = $prefix . $v['product']['picture'];
  34. }
  35. //多图
  36. $v['product']['pictures'] = array_map(function ($v) use ($prefix) {
  37. return strpos($v, $prefix) === false ? $prefix . $v : $v;
  38. }, $v['product']['pictures']);
  39. }
  40. }
  41. }
  42. }
  43. return $this->success($list);
  44. }
  45. public function create()
  46. {
  47. $id = (int)request()->input('agent_product_id');
  48. $agent_product = AgentProduct::find($id);
  49. if (!$agent_product) {
  50. return $this->error('产品不存在或已被删除');
  51. }
  52. //如果不存在则创建
  53. UserFav::query()->firstOrCreate([
  54. 'user_id' => $this->user_id,
  55. 'agent_product_id' => $agent_product->id,
  56. 'product_id' => $agent_product->product_id,
  57. ]);
  58. return $this->success();
  59. }
  60. public function delete()
  61. {
  62. $id = (int)request()->input('agent_product_id');
  63. $fav = UserFav::query()->where([
  64. 'user_id' => $this->user_id,
  65. 'agent_product_id' => $id,
  66. ])->first();
  67. if (!$fav) {
  68. return $this->error('收藏不存在');
  69. }
  70. $fav->delete();
  71. return $this->success();
  72. }
  73. }