AccountController.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use Carbon\Carbon;
  5. use Auth, Cache, Redis;
  6. use App\{Notification, Profile, User};
  7. class AccountController extends Controller
  8. {
  9. public function __construct()
  10. {
  11. $this->middleware('auth');
  12. }
  13. public function notifications(Request $request)
  14. {
  15. $this->validate($request, [
  16. 'page' => 'nullable|min:1|max:3'
  17. ]);
  18. $profile = Auth::user()->profile;
  19. $timeago = Carbon::now()->subMonths(6);
  20. $notifications = Notification::whereProfileId($profile->id)
  21. ->whereDate('created_at', '>', $timeago)
  22. ->orderBy('id','desc')
  23. ->take(30)
  24. ->simplePaginate();
  25. return view('account.activity', compact('profile', 'notifications'));
  26. }
  27. public function fetchNotifications($id)
  28. {
  29. $key = config('cache.prefix') . ":user.{$id}.notifications";
  30. $redis = Redis::connection();
  31. $notifications = $redis->lrange($key, 0, 30);
  32. if(empty($notifications)) {
  33. $notifications = Notification::whereProfileId($id)
  34. ->orderBy('id','desc')->take(30)->get();
  35. } else {
  36. $notifications = $this->hydrateNotifications($notifications);
  37. }
  38. return $notifications;
  39. }
  40. public function hydrateNotifications($keys)
  41. {
  42. $prefix = 'notification.';
  43. $notifications = collect([]);
  44. foreach($keys as $key) {
  45. $notifications->push(Cache::get("{$prefix}{$key}"));
  46. }
  47. return $notifications;
  48. }
  49. }