cyrildewit / eloquent-viewable

Associate views with Eloquent models in Laravel
MIT License
803 stars 104 forks source link

How can I check if an auth user or a visitor has already viewed a post? #279

Open Fajendagba opened 1 year ago

Fajendagba commented 1 year ago

I need to be able to know if the current visitor has already viewed a post or not. I want this to be able to sort post orderBy post not yet viewed.

I also need to know if the current Auth user has already viewed a post, so that post can be sorted by post not yet viewed.

I've read many blogs and articles, but found none useful.

iamB0rgy commented 1 year ago

I need to be able to know if the current visitor has already viewed a post or not. I want this to be able to sort post orderBy post not yet viewed.

I also need to know if the current Auth user has already viewed a post, so that post can be sorted by post not yet viewed.

I've read many blogs and articles, but found none useful.

Hi @Fajendagba, are you able to get it? I need the same requirement.

Fajendagba commented 1 year ago

No @iamB0rgy I haven't seen the solution. But in case you get it first, please drop it here. Thank you.

Rubdui commented 1 year ago

I am also searching for the same , any solutions?

Fajendagba commented 1 year ago

@iamB0rgy @iamB0rgy the solution is actually simpler than I thought. Here it is

public function home(Request $request, Visitor $visitor)
{
    $visitorId = $visitor->id();

    // Get all post that hasn't been viewed by the visitor yet
    // Make sure your Post model implements Viewable
    $postsNotYetViewed = Post::whereIn('id', $posts->pluck('id'))
        ->whereDoesntHave('views', function ($query) use ($visitorId) {
            $query->where('visitor', $visitorId);
        })
        ->orderBy('created_at', 'desc')
        ->paginate($limit);

    return view('post', [
        'posts' => $posts,
    ]);
}

MirrorVlogger