In Laravel, posts and categories having many to many relationship. That means one post can have multiple categories. In that case, I want to show related posts by current categories. However I've achieve this by storing current category id in session. But the problem occurs when a post has multiple categories and all are open in different tabs navigated from its respective categories. If I refresh them, related posts are changed to latest category stored in session.
Please suggest a way to solve this. Thank you all in advance. :)
$category[] = $request->session()->get('current_category_id');
$relatedPosts = Post::whereHas('category', function($q) use ($category) {
$q->whereIn('category_id',$category);
})->whereNotIn('id', $currentPost->id)->take(5)->get();
Expected: After refresh, page should show related posts of the category navigated from.
Actual: After refresh, pages are showing related posts of latest category navigated from.
For this sort of thing I would normally add 'tags' and tag posts with keywords which then allow display of related posts based on highest number of matching tags (some of your own logic will be required here)
The library I have used in the past is: https://github.com/spatie/laravel-tags
Relying on sessions is difficult, especially since people could end up on your article page directly from a search engine so would have no session history