LikeController.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Jobs\LikePipeline\LikePipeline;
  4. use App\Jobs\LikePipeline\UnlikePipeline;
  5. use App\Like;
  6. use App\Status;
  7. use App\User;
  8. use Auth;
  9. use Cache;
  10. use Illuminate\Http\Request;
  11. use App\Services\StatusService;
  12. class LikeController extends Controller
  13. {
  14. public function __construct()
  15. {
  16. $this->middleware('auth');
  17. }
  18. public function store(Request $request)
  19. {
  20. $this->validate($request, [
  21. 'item' => 'required|integer|min:1',
  22. ]);
  23. $user = Auth::user();
  24. $profile = $user->profile;
  25. $status = Status::findOrFail($request->input('item'));
  26. if (Like::whereStatusId($status->id)->whereProfileId($profile->id)->exists()) {
  27. $like = Like::whereProfileId($profile->id)->whereStatusId($status->id)->firstOrFail();
  28. UnlikePipeline::dispatch($like);
  29. } else {
  30. abort_if(
  31. Like::whereProfileId($user->profile_id)
  32. ->where('created_at', '>', now()->subDay())
  33. ->count() >= Like::MAX_PER_DAY,
  34. 429
  35. );
  36. $count = $status->likes_count > 4 ? $status->likes_count : $status->likes()->count();
  37. $like = Like::firstOrCreate([
  38. 'profile_id' => $user->profile_id,
  39. 'status_id' => $status->id
  40. ]);
  41. if($like->wasRecentlyCreated == true) {
  42. $count++;
  43. $status->likes_count = $count;
  44. $like->status_profile_id = $status->profile_id;
  45. $like->is_comment = in_array($status->type, [
  46. 'photo',
  47. 'photo:album',
  48. 'video',
  49. 'video:album',
  50. 'photo:video:album'
  51. ]) == false;
  52. $like->save();
  53. $status->save();
  54. LikePipeline::dispatch($like);
  55. }
  56. }
  57. Cache::forget('status:'.$status->id.':likedby:userid:'.$user->id);
  58. StatusService::refresh($status->id);
  59. if ($request->ajax()) {
  60. $response = ['code' => 200, 'msg' => 'Like saved', 'count' => 0];
  61. } else {
  62. $response = redirect($status->url());
  63. }
  64. return $response;
  65. }
  66. }