BlogComposer.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace App\Http\ViewComposers;
  3. use App\Models\BlogArticle;
  4. use App\Models\BlogCategory;
  5. use App\Models\BlogTag;
  6. use Illuminate\Support\Facades\Auth;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\View\View;
  9. use App\Models\User;
  10. class BlogComposer
  11. {
  12. // 博客信息
  13. protected $blogInfo = [];
  14. protected $userId = '1';
  15. /**
  16. * 创建一个新的 profile composer
  17. *
  18. * @return void
  19. */
  20. public function __construct(BlogArticle $article)
  21. {
  22. $articles = BlogArticle::all();
  23. $articles = $articles->toArray();
  24. // 汇总信息
  25. $this->blogInfo['collect'] = [
  26. 'article_num'=> count($articles),// 文章数
  27. 'view_count_num'=> array_sum(array_column($articles, 'view_count')), // 总查看数
  28. 'reply_count_num'=> array_sum(array_column($articles, 'reply_count')),// 总评论数
  29. ];
  30. // 文章归档
  31. $this->blogInfo['groupTime'] = [];
  32. foreach ($articles as $item){
  33. $a = strtotime($item['created_at']);
  34. $key = date('Y', $a) . date('m', $a);
  35. if (array_key_exists($key, $this->blogInfo['groupTime'])) {
  36. $this->blogInfo['groupTime'][$key]['num'] = $this->blogInfo['groupTime'][$key]['num'] + 1;
  37. } else {
  38. $this->blogInfo['groupTime'][$key]['name'] = date('Y', $a) . ' 年 ' . date('m', $a) . ' 月';
  39. $this->blogInfo['groupTime'][$key]['num'] = 1;
  40. }
  41. }
  42. // 个人分类
  43. $this->blogInfo['categories'] = BlogCategory::where('user_id', $this->userId)->get()->toArray();
  44. // 标签云
  45. // $this->blogInfo['tags'] = BlogTag::all();
  46. $this->blogInfo['tags'] = DB::select(
  47. DB::raw("SELECT A.*,COUNT(B.id) AS count_num FROM `blog_tags` AS A LEFT JOIN blog_tags_link_articles AS B ON A.id=B.tag_id GROUP BY A.id")
  48. );
  49. // 最新文章
  50. $this->blogInfo['articles_news'] = array_sort($articles, function ($a, $b){
  51. return strtotime($b['created_at']) - strtotime($a['created_at']);
  52. });
  53. $this->blogInfo['articles_news'] = array_slice($this->blogInfo['articles_news'], 0, 5);
  54. // 最受欢迎
  55. $this->blogInfo['articles_hots'] = array_sort($articles, function ($a, $b){
  56. return (int) $b['view_count'] - (int) $a['view_count'];
  57. });
  58. $this->blogInfo['articles_hots'] = array_slice($this->blogInfo['articles_hots'], 0, 5);
  59. }
  60. /**
  61. * 将数据绑定到视图。
  62. *
  63. * @param View $view
  64. * @return void
  65. */
  66. public function compose(View $view)
  67. {
  68. $view->with(['common'=> [
  69. 'blogInfo'=> $this->blogInfo,
  70. ]]);
  71. }
  72. }