Latest

Thursday, July 13, 2017

Laravel, how to create an article reader count on a blog using cookies

Asked by: Alex Chan


I have a script like this :

public function read($slug,$read_more){
    $artikel = App\Post::where('read_more',$read_more)->first();
    $comments = App\Comment::where('post_id',$artikel->id)->where('active','1')->get();
    $pops = App\Post::orderBy('count','desc')->limit(5)->get();
    $coms = App\Comment::orderBy('active','desc')->orderBy('created_at','desc')->limit(5)->get();
    $categorys = App\Category::all();
    $title = 'Artikel '.$artikel->category->category.' » '.$artikel->title;
    $description = str_limit($artikel->content,70);
    $keywords = $artikel->category->category.', teknologi, komputer, artikel, pemrograman, informasi, terbaru, linux';

    $view = view('guest.read',compact('artikel','comments','categorys','title','description','keywords','pops','coms'));
    if(Cookie::get('__urda')==$artikel->id){
        return $view;
    }else{
        $count = App\Post::find($artikel->id);
        $count->count = $artikel->count+1;
        $count->save();
        $cookie = new Response($view);
        $cookie->withCookie(cookie()->forever('__urda',$artikel->id));
        return $cookie;
    }
}

Problem while reading the article.

If you read article A, the number of readers increases.

If you read article B, the number of readers increases.

If you reread article A, the number of readers will increase again. (Should not increase)

example : http://www.jinggacloud.com

What is the solution



Source

No comments:

Post a Comment

Adbox