Home > Back-end >  Send notification to creator on the basis of post page views in laravel?
Send notification to creator on the basis of post page views in laravel?

Time:10-15

I want to send the notification to the post creator on the basis of page views in laravel. Like when the post gets 1000 views, the creator should get a congratulatory notification. Here the problem is I am using cookies(2 hours) to prevent multiple page views. so the creator gets multiple notifications until views are moved to 1001.

if($views == 1000){
        $user = User::find($userid);
        $notificationdetails = [
          'subject' => 'Congratulations, You got your first '.$views. ' views on your new snippet - '.$snippet_title,
          'greeting' => 'Hi, '.$user->name,
          'body' => 'Congratulations, You got your first '.$views. ' views on your new 
     snippet - '.$snippet_title,
          'body1' =>'',
          'thanks' => ' ',
          'actionText' => 'View snippet',
          'actionURL' => url(env('FRONTEND_URL').'/snippets/'.$slug)
                 ];
          Notification::send($user, new BBBnotifications($notificationdetails));

    }

CodePudding user response:

You have to implement your logic while you update the view, not while fetching the count. You could follow this approach.


$cookieName = "post_".$postId; // using postId to determine each post

//check if the cookie exists
if(!isset($_COOKIE[$cookieName])) {

   //increase view count on post table of `$postId`
  
  setcookie($cookieName, true, time()   (3600 * 2));
}

You could leave your current notifications sending logic as it is (if it is working), because, now on view count will be updated only when there is no cookie set.

CodePudding user response:

You can create a table in your DB and check if notification sent or read. First you should create a model and related table.

if($views == 1000){
        $user = User::find($userid);
        $notification_check = NotificationHistory::where('user_id', $user->id)->where('notification_type', 1000)->first();

        if($notification_check === null)
          {
        $notificationdetails = [
          'subject' => 'Congratulations, You got your first '.$views. ' views on your new snippet - '.$snippet_title,
          'greeting' => 'Hi, '.$user->name,
          'body' => 'Congratulations, You got your first '.$views. ' views on your new 
     snippet - '.$snippet_title,
          'body1' =>'',
          'thanks' => ' ',
          'actionText' => 'View snippet',
          'actionURL' => url(env('FRONTEND_URL').'/snippets/'.$slug),
          'type' => 1000
                 ];
          
          Notification::send($user, new BBBnotifications($notificationdetails));
          NotificationHistory::create([
          'notification_type' => 1000,
          'user_id' => $user->id, //or auth()->user()->id
          'read_at' => now()
          ]);
        }
    }
  • Related