PlanController.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace App\Http\Controllers\User;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\User;
  5. use Illuminate\Http\Request;
  6. use App\Models\Plan;
  7. use Illuminate\Support\Facades\DB;
  8. class PlanController extends Controller
  9. {
  10. public function fetch(Request $request)
  11. {
  12. $user = User::find($request->session()->get('id'));
  13. if ($request->input('id')) {
  14. $plan = Plan::where('id', $request->input('id'))->first();
  15. if (!$plan) {
  16. abort(500, __('Subscription plan does not exist'));
  17. }
  18. if ((!$plan->show && !$plan->renew) || (!$plan->show && $user->plan_id !== $plan->id)) {
  19. abort(500, __('Subscription plan does not exist'));
  20. }
  21. return response([
  22. 'data' => $plan
  23. ]);
  24. } else {
  25. $counts = User::select(
  26. DB::raw("plan_id"),
  27. DB::raw("count(*) as count")
  28. )
  29. ->where('plan_id', '!=', NULL)
  30. ->where(function ($query) {
  31. $query->where('expired_at', '>=', time())
  32. ->orWhere('expired_at', NULL);
  33. })
  34. ->groupBy("plan_id")
  35. ->get()
  36. ->keyBy('plan_id');
  37. }
  38. $plans = Plan::where('show', 1)
  39. ->orderBy('sort', 'ASC')
  40. ->get();
  41. if (isset($counts)) {
  42. foreach ($plans as $k => $v) {
  43. if ($plans[$k]->capacity_limit === NULL) continue;
  44. if (!isset($counts[$plans[$k]->id])) continue;
  45. $plans[$k]->capacity_limit = $plans[$k]->capacity_limit - $counts[$plans[$k]->id]->count;
  46. }
  47. }
  48. return response([
  49. 'data' => $plans
  50. ]);
  51. }
  52. }