2017-07-31 25 views
2

計數頁面訪問量我要實現我的應用程序頁面視圖計數器。與Laravel

public function showpost($titleslug) { 
     $post = Post::where('titleslug','=',$titleslug)->firstOrFail(); 
     $viewed = Session::get('viewed_post', []); 
     if (!in_array($post->id, $viewed)) { 
      $post->increment('views'); 
      Session::push('viewed_post', $post->id); 
     } 
     return view('posts/show', compact('post', $post)); 
    } 

我檢索熱門帖子列表這樣的:使用這種方法我到目前爲止已經做的是

$popular_posts = Post::orderBy('views', 'desc')->take(10)->get(); 

不過,我想知道是否有任何更好的方法來做這個 ?用我目前的方法,我可以在過去24小時內得到最多查看的帖子列表嗎?這一切,並感謝!

+0

如果你店裏當一個網頁被瀏覽,你可以得到的信息,但如果你只使用一個計數器的時間被視爲一個職位,你不能排序觀看次數最多的去年x分鐘的量。 – milo526

+0

「應用程序」有多大(換言之,我會說網頁),換句話說有多少用戶是最高峯?或者如果你有統計資料,在峯值期間有多少請求/米?你使用什麼會話驅動程序?頁面視圖僅與顯示大多數瀏覽過的頁面有關,或者稍後您將使用數據(也許是「30天前前10個文章/頁面」等等)。 – Kyslik

+0

那麼,這意味着我需要創建一個不同的表來存儲視圖數據。 @ milo526 –

回答

4

正如@ milo526的評論報價,你可以記錄,而不是一個獨特的方式增量全部命中到您的網頁。有了這個,您可以搜索訪問信息,包括根據大多數瀏覽次數排序的帖子列表。

創建一個表,以節省您的視圖記錄:

Schema::create("posts_views", function(Blueprint $table) 
     { 
      $table->engine = "InnoDB"; 

      $table->increments("id"); 
      $table->increments("id_post"); 
      $table->string("titleslug"); 
      $table->string("url"); 
      $table->string("session_id"); 
      $table->string("user_id"); 
      $table->string("ip"); 
      $table->string("agent"); 
      $table->timestamps(); 
     }); 

然後,創建相應的模型:

<?php namespace App\Models; 

class PostsViews extends \Eloquent { 

    protected $table = 'posts_views'; 

    public static function createViewLog($post) { 
      $postsViews= new PostsViews(); 
      $postsViews->id_post = $post->id; 
      $postsViews->titleslug = $post->titleslug; 
      $postsViews->url = \Request::url(); 
      $postsViews->session_id = \Request::getSession()->getId(); 
      $postsViews->user_id = \Auth::user()->id; 
      $postsViews->ip = \Request::getClientIp(); 
      $postsViews->agent = \Request::header('User-Agent'); 
    } 

} 

最後,你的方法:

public function showpost($titleslug) 
{ 
    $post = PostsViews::where('titleslug', '=' ,$titleslug)->firstOrFail(); 

    PostsViews::createViewLog($post); 

    //Rest of method... 
} 

要搜索的最在過去24小時內觀看帖子:

$posts = Posts::join("posts_views", "posts_views.id_post", "=", "posts.id") 
      ->where("created_at", ">=", date("Y-m-d H:i:s", strtotime('-24 hours', time()))) 
      ->groupBy("posts.id") 
      ->orderBy(DB::raw('COUNT(posts.id)', 'desc')) 
      ->get(array(DB::raw('COUNT(posts.id) as total_views'), 'posts.*')); 

注意,在PostsViews,你有數據,可以幫助進一步篩選您的物品,如會話ID,如果你不想考慮來自同一會話命中。

您可能需要這種解決方案的某些方面適應你的最終代碼。

+0

我會試試這個,但我想知道是否必須定義'post_views'表和'posts'表? –

+0

我不得不改變一些東西,但你給了我這個想法,我會在完成後發佈我的修改版本。謝謝! –

+0

這是一個偉大的概念!對於我正在開發的一個項目,我也略微調整了它。你可能會考慮更新createViewLog()來調用$ postsViews-> save()。否則,日誌條目將不會被插入到表中。 – Benco