-> php artisan make:model PostView -m
->add column for views in post table
public function postView()
{
return $this->hasMany(PostView::class);
}
public function postView(){
$this->belongsTo(Post::class);
}
public static function createViewLog($post) {
$postViews= new ArticleView();
$postViews->post_id = $post->id;
$postViews->post_slug = Str::slug($post->title);
$postViews->url = request()->url();
$postViews->session_id = request()->getSession()->getId();
$postViews->user_id = (auth()->check())?auth()->id():null;
$postViews->ip = request()->ip();
$postViews->agent = request()->header('User-Agent');
$postViews->save();
}
public function show(Post $post)
{
$post = Post::with('category', 'user')->find($post->id);
$viewed = Session::get('viewed_post', []);
if (!in_array($post->id, $viewed)) {
$post->increment('views');
PostView::createViewLog($post);
Session::push('viewed_post', $post->id);
}
return $post;
}
{{$post->views}}
OR
{{\App\Models\ArticleView::where('post_id',$post->id)->count('post_id')}}