Search code examples
phplaravellaravel-5laravel-8

Send notification to creator on the basis of post page views in laravel?


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));

    }

Solution

  • 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()
              ]);
            }
        }