Session, Popular post and View Count I'm making a popular blogs display based on view count but I'm having problem using session.
My blog show method
public function show(Request $request, $id)
{
if (Session::get('id') !== $id) {
Post::where('id', $id)->increment('view_count');
Session::put('id', $id);
}
$comments = Comment::where('blog_id', $id)->with('user')->orderBy('created_at', 'ASC')->paginate(4);
$blogs = Post::where('id', $id)->with('user')->first();
a user only updates the count when he viewed it once
but when a user keeps changing between two blogs the two blogs keeps incrementing by 1.
can you please suggest the best and easiest way to solve this problem. thank you!
There are many ways to do this,..
Basically you need to save the Id of all blogs the user views. So we need to a save an array or we could format the session keys like blog_1 where 1 is the Id.
$blogKey = 'blog_' . $id;
// Check if blog session key exists
// If not, update view_count and create session key
if (!Session::has($blogKey)) {
Post::where('id', $id)->increment('view_count');
Session::put($blogkey, 1);
}
@Prez amazing!!! I've been testing this for hours and you solved it easily.
@Eco012390 you'll get there, I've been doing this on and off for ~20 years.
I searched many articles on the internet, and found many complicated solutions, but your answer is great and works as expected ... Thank you very much
how can we increment more than 1 time . i want to show more view count in my blog.
please help me
Please sign in or create an account to participate in this conversation.