AccountController.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. $notifications = Notification::whereProfileId($profile->id)
  17. ->orderBy('id','desc')->take(30)->simplePaginate();
  18. return view('account.activity', compact('profile', 'notifications'));
  19. }
  20. public function fetchNotifications($id)
  21. {
  22. $key = config('cache.prefix') . ":user.{$id}.notifications";
  23. $redis = Redis::connection();
  24. $notifications = $redis->lrange($key, 0, 30);
  25. if(empty($notifications)) {
  26. $notifications = Notification::whereProfileId($id)
  27. ->orderBy('id','desc')->take(30)->get();
  28. } else {
  29. $notifications = $this->hydrateNotifications($notifications);
  30. }
  31. return $notifications;
  32. }
  33. public function hydrateNotifications($keys)
  34. {
  35. $prefix = 'notification.';
  36. $notifications = collect([]);
  37. foreach($keys as $key) {
  38. $notifications->push(Cache::get("{$prefix}{$key}"));
  39. }
  40. return $notifications;
  41. }
  42. }