AccountController.php 1.2 KB

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