BlogArticlesController.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Models\BlogArticle;
  4. use http\Env\Response;
  5. use Illuminate\Http\Request;
  6. use Illuminate\Support\Facades\Cache;
  7. class BlogArticlesController extends Controller
  8. {
  9. // 文章点赞
  10. public function upvote(BlogArticle $article)
  11. {
  12. $ip = \request()->getClientIp();
  13. //先进行判断是否已经 浏览过
  14. if (!$this->_hasVote($article, $ip)) {
  15. // 保存到数据库
  16. $article->vote_count = $article->vote_count + 1;
  17. $article->save();
  18. // 保存到 Session
  19. $this->_storeVote($article, $ip);
  20. return \response([
  21. 'vote_count' => $article->vote_count,
  22. 'status' => 1,
  23. 'msg' => '点赞成功',
  24. ], 200);
  25. } else {
  26. return \response([
  27. 'status' => 0,
  28. 'msg' => '您已经赞过了',
  29. ], 200);
  30. }
  31. }
  32. // 判断是否存在
  33. protected function _hasVote($article, $ip)
  34. {
  35. return Cache::has('upvote_Articles_' . $ip. $article->id);
  36. }
  37. protected function _getVote($article, $ip)
  38. {
  39. return Cache::get('upvote_Articles_' . $ip. $article->id);
  40. }
  41. // 将保存到 Session
  42. protected function _storeVote($article, $ip)
  43. {
  44. $key = 'upvote_Articles_' . $ip . $article->id;
  45. // 24 小时过期
  46. Cache::put($key, time(), 24 * 60);
  47. }
  48. }