Well this question is 9 months old so i'm not sure if OP is still in the need of an answer but due the many views and the tasty bounty I would like to also add my mustard (German saying..).

In this post I will try to make a simple explained example on how to start building a notification system.

Edit: Well ok this turned out way, way, way longer than I expected it to be. I got really tired in the end, i'm sorry.

WTLDR;

Question 1: have a flag on every notification.

Question 2: Still store every notification as a single record inside your database and group them when they are requested.


Structure

I assume that the notifications will look something like:

+---------------------------------------------+
| ▣ James has uploaded new Homework: Math 1+1 |
+---------------------------------------------+
| ▣ Jane and John liked your comment: Im s... | 
+---------------------------------------------+
| ▢ The School is closed on independence day. |
+---------------------------------------------+

Behind the curtains this could look something like this:

+--------+-----------+--------+-----------------+-------------------------------------------+
| unread | recipient | sender | type            | reference                                 |
+--------+-----------+--------+-----------------+-------------------------------------------+
| true   | me        | James  | homework.create | Math 1 + 1                                |
+--------+-----------+--------+-----------------+-------------------------------------------+
| true   | me        | Jane   | comment.like    | Im sick of school                         |
+--------+-----------+--------+-----------------+-------------------------------------------+
| true   | me        | John   | comment.like    | Im sick of school                         |
+--------+-----------+--------+-----------------+-------------------------------------------+
| false  | me        | system | message         | The School is closed on independence day. |
+--------+-----------+--------+-----------------+-------------------------------------------+

Note: I don't recommend to group the notifications inside the database, do that on runtime this keeps things a lot more flexible.

  • Unread
    Every notification should have a flag to indicate if the recipient has already opened the notification.
  • Recipient
    Defines who receives the notification.
  • Sender
    Defines who triggered the notification.
  • Type
    Instead of having every Message in plain text inside your database create types. This way you can create special handlers for different notification types inside your backend. Will reduce the amount of data stored inside your database and gives your even more flexibility, enabled easy translating of notification, changes of past messages etc..
  • Reference
    Most notifications will have a Reference to a record on your database or your application.

Every system I have been working on had a simple 1 to 1 reference relationship on a notification, you might have an 1 to n keep in mind that I will continue my example with 1:1. This also means that I don't need a field defining what type of object is referenced because this is defined by the notification type.

SQL Table

Now when defining a real table structure for SQL we come to a few decisions in terms of the database design. I will go with simplest solution which will look something like this:

+--------------+--------+---------------------------------------------------------+
| column       | type   | description                                             |
+--------------+--------+---------------------------------------------------------+
| id           | int    | Primary key                                             |
+--------------+--------+---------------------------------------------------------+
| recipient_id | int    | The receivers user id.                                  |
+--------------+--------+---------------------------------------------------------+
| sender_id    | int    | The sender's user id.                                   |
+--------------+--------+---------------------------------------------------------+
| unread       | bool   | Flag if the recipient has already read the notification |
+--------------+--------+---------------------------------------------------------+
| type         | string | The notification type.                                  |
+--------------+--------+---------------------------------------------------------+
| parameters   | array  | Additional data to render different notification types. |
+--------------+--------+---------------------------------------------------------+
| reference_id | int    | The primary key of the referencing object.              |
+--------------+--------+---------------------------------------------------------+
| created_at   | int    | Timestamp of the notification creation date.            |
+--------------+--------+---------------------------------------------------------+

Or for the lazy folks the SQL create table command for this example:

CREATE TABLE `notifications` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `recipient_id` int(11) NOT NULL,
  `sender_id` int(11) NOT NULL,
  `unread` tinyint(1) NOT NULL DEFAULT '1',
  `type` varchar(255) NOT NULL DEFAULT '',
  `parameters` text NOT NULL,
  `reference_id` int(11) NOT NULL,
  `created_at` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

PHP Service

This implementation depends completely on the needs of your application, Note: This is an example not the golden standard on how to build an notification system in PHP.

Notification model

This is an example base model of the notification itself, nothing fancy just the needed properties and the abstract methods messageForNotification and messageForNotifications we expected being implemented in the different notification types.

abstract class Notification
{
    protected $recipient;
    protected $sender;
    protected $unread;
    protected $type;
    protected $parameters;
    protected $referenceId;
    protected $createdAt;

    /**
     * Message generators that have to be defined in subclasses
     */
    public function messageForNotification(Notification $notification) : string;
    public function messageForNotifications(array $notifications) : string;

    /**
     * Generate message of the current notification.
     */ 
    public function message() : string
    {
        return $this->messageForNotification($this);
    }
}

You will have to add a constructor, getters, setters and that kind of stuff by yourself in your own style, i'm not going to provide a ready to use Notification system.

Notification Types

Now you can create a new Notification subclass for every type. This following example would handle the like action of a comment:

  • Ray has liked your comment. (1 notification)
  • John and Jane liked your comment. (2 notifications)
  • Jane, Johnny, James and Jenny liked your comment. (4 notifications)
  • Jonny, James and 12 others liked your comment. (14 notifications)

Example implementation:

namespace Notification\Comment;

class CommentLikedNotification extends \Notification
{
    /**
     * Generate a message for a single notification
     * 
     * @param Notification              $notification
     * @return string 
     */
    public function messageForNotification(Notification $notification) : string 
    {
        return $this->sender->getName() . 'has liked your comment: ' . substr($this->reference->text, 0, 10) . '...'; 
    }

    /**
     * Generate a message for a multiple notifications
     * 
     * @param array              $notifications
     * @return string 
     */
    public function messageForNotifications(array $notifications, int $realCount = 0) : string 
    {
        if ($realCount === 0) {
            $realCount = count($notifications);
        }

        // when there are two 
        if ($realCount === 2) {
            $names = $this->messageForTwoNotifications($notifications);
        }
        // less than five
        elseif ($realCount < 5) {
            $names = $this->messageForManyNotifications($notifications);
        }
        // to many
        else {
            $names = $this->messageForManyManyNotifications($notifications, $realCount);
        }

        return $names . ' liked your comment: ' . substr($this->reference->text, 0, 10) . '...'; 
    }

    /**
     * Generate a message for two notifications
     *
     *      John and Jane has liked your comment.
     * 
     * @param array              $notifications
     * @return string 
     */
    protected function messageForTwoNotifications(array $notifications) : string 
    {
        list($first, $second) = $notifications;
        return $first->getName() . ' and ' . $second->getName(); // John and Jane
    }

    /**
     * Generate a message many notifications
     *
     *      Jane, Johnny, James and Jenny has liked your comment.
     * 
     * @param array              $notifications
     * @return string 
     */
    protected function messageForManyNotifications(array $notifications) : string 
    {
        $last = array_pop($notifications);

        foreach($notifications as $notification) {
            $names .= $notification->getName() . ', ';
        }

        return substr($names, 0, -2) . ' and ' . $last->getName(); // Jane, Johnny, James and Jenny
    }

    /**
     * Generate a message for many many notifications
     *
     *      Jonny, James and 12 other have liked your comment.
     * 
     * @param array              $notifications
     * @return string 
     */
    protected function messageForManyManyNotifications(array $notifications, int $realCount) : string 
    {
        list($first, $second) = array_slice($notifications, 0, 2);

        return $first->getName() . ', ' . $second->getName() . ' and ' .  $realCount . ' others'; // Jonny, James and 12 other
    }
}

Notification manager

To work with your notifications inside your application create something like a notification manager:

class NotificationManager
{
    protected $notificationAdapter;

    public function add(Notification $notification);

    public function markRead(array $notifications);

    public function get(User $user, $limit = 20, $offset = 0) : array;
}

The notificationAdapter property should contain the logic in direct communication with your data backend in the case of this example mysql.

Creating notifications

Using mysql triggers is not wrong, because there is no wrong solution. What works, works.. But I strongly recommend to not let the database handle application logic.

So inside the notification manager you might want to do something like this:

public function add(Notification $notification)
{
    // only save the notification if no possible duplicate is found.
    if (!$this->notificationAdapter->isDoublicate($notification))
    {
        $this->notificationAdapter->add([
            'recipient_id' => $notification->recipient->getId(),
            'sender_id' => $notification->sender->getId()
            'unread' => 1,
            'type' => $notification->type,
            'parameters' => $notification->parameters,
            'reference_id' => $notification->reference->getId(),
            'created_at' => time(),
        ]);
    }
}

Behind the add method of the notificationAdapter can be a raw mysql insert command. Using this adapter abstraction enables you to switch easily from mysql to a document based database like mongodb which would make sense for a Notification system.

The isDoublicate method on the notificationAdapter should simply check if there is already a notification with the same recipient, sender, type and reference.


I cannot point out enough that this is only a example. (Also I really have to shorten the next steps this post is getting ridiculously long -.-)


So assuming you have some kind of controller with an action when a teacher uploads homework:

function uploadHomeworkAction(Request $request)
{
    // handle the homework and have it stored in the var $homework.

    // how you handle your services is up to you...
    $notificationManager = new NotificationManager;

    foreach($homework->teacher->students as $student)
    {
        $notification = new Notification\Homework\HomeworkUploadedNotification;
        $notification->sender = $homework->teacher;
        $notification->recipient = $student;
        $notification->reference = $homework;

        // send the notification
        $notificationManager->add($notification);
    }
}

Will create a notification for every teacher's student when he uploads a new homework.

Reading the notifications

Now comes the hard part. The problem with grouping on the PHP side is that you will have to load all notifications of the current user to group them correctly. This would be bad, well if you have only a few users it would probably still be no problem, but that doesn't make it good.

The easy solution is to simply limit the number of notifications requested and only grouping these. This will work fine when there are not many similar notifications (like 3-4 per 20). But lets say the post of a user / student gets about a hundred likes and you only select the last 20 notifications. The user will then only see that 20 people liked his post also that would be his only notification.

A "correct" solution would be grouping the notifications already on the database and selecting only some samples per notification group. Than you would just have to inject the real count into your notification messages.

You probably didn't read the text below so let me continue with a snippet:

select *, count(*) as count from notifications
where recipient_id = 1
group by `type`, `reference_id`
order by created_at desc, unread desc
limit 20

Now you know what notifications should be around for the given user and how many notifications the group contains.

And now the shitty part. I still could not find out a better way to select a limited number of notifications for each group without doing a query for every group. All suggestions here are very welcome.

So I do something like:

$notifcationGroups = [];

foreach($results as $notification)
{
    $notifcationGroup = ['count' => $notification['count']];

    // when the group only contains one item we don't 
    // have to select it's children
    if ($notification['count'] == 1)
    {
        $notifcationGroup['items'] = [$notification];
    }
    else
    {
        // example with query builder
        $notifcationGroup['items'] = $this->select('notifications')
            ->where('recipient_id', $recipient_id)
            ->andWehere('type', $notification['type'])
            ->andWhere('reference_id', $notification['reference_id'])
            ->limit(5);
    }

    $notifcationGroups[] = $notifcationGroup;
}

I will now continue assuming that the notificationAdapters get method implements this grouping and returns an array like this:

[
    {
        count: 12,
        items: [Note1, Note2, Note3, Note4, Note5] 
    },
    {
        count: 1,
        items: [Note1] 
    },
    {
        count: 3,
        items: [Note1, Note2, Note3] 
    }
]

Because we always have at least one notification in our group and our ordering prefers Unread and New notifications we can just use the first notification as a sample for rendering.

So to be able to work with these grouped notifications we need a new object:

class NotificationGroup
{
    protected $notifications;

    protected $realCount;

    public function __construct(array $notifications, int $count)
    {
        $this->notifications = $notifications;
        $this->realCount = $count;
    }

    public function message()
    {
        return $this->notifications[0]->messageForNotifications($this->notifications, $this->realCount);
    }

    // forward all other calls to the first notification
    public function __call($method, $arguments)
    {
        return call_user_func_array([$this->notifications[0], $method], $arguments);
    }
}

And finally we can actually put most of the stuff together. This is how the get function on the NotificationManager might look like:

public function get(User $user, $limit = 20, $offset = 0) : array
{
    $groups = [];

    foreach($this->notificationAdapter->get($user->getId(), $limit, $offset) as $group)
    {
        $groups[] = new NotificationGroup($group['notifications'], $group['count']);
    }

    return $gorups;
}

And really finally inside a possible controller action:

public function viewNotificationsAction(Request $request)
{
    $notificationManager = new NotificationManager;

    foreach($notifications = $notificationManager->get($this->getUser()) as $group)
    {
        echo $group->unread . ' | ' . $group->message() . ' - ' . $group->createdAt() . "\n"; 
    }

    // mark them as read 
    $notificationManager->markRead($notifications);
}
Answer from Mario on Stack Overflow
🌐
Cloudways
cloudways.com › home › creating real time notification system in php and ajax polling
Create Real Time Notification System in PHP with Ajax
4 weeks ago - Integrate a push notification service to send messages to users. Develop frontend handling to display these notifications to users. Allow users to set their preferences for receiving notifications.
Top answer
1 of 4
204

Well this question is 9 months old so i'm not sure if OP is still in the need of an answer but due the many views and the tasty bounty I would like to also add my mustard (German saying..).

In this post I will try to make a simple explained example on how to start building a notification system.

Edit: Well ok this turned out way, way, way longer than I expected it to be. I got really tired in the end, i'm sorry.

WTLDR;

Question 1: have a flag on every notification.

Question 2: Still store every notification as a single record inside your database and group them when they are requested.


Structure

I assume that the notifications will look something like:

+---------------------------------------------+
| ▣ James has uploaded new Homework: Math 1+1 |
+---------------------------------------------+
| ▣ Jane and John liked your comment: Im s... | 
+---------------------------------------------+
| ▢ The School is closed on independence day. |
+---------------------------------------------+

Behind the curtains this could look something like this:

+--------+-----------+--------+-----------------+-------------------------------------------+
| unread | recipient | sender | type            | reference                                 |
+--------+-----------+--------+-----------------+-------------------------------------------+
| true   | me        | James  | homework.create | Math 1 + 1                                |
+--------+-----------+--------+-----------------+-------------------------------------------+
| true   | me        | Jane   | comment.like    | Im sick of school                         |
+--------+-----------+--------+-----------------+-------------------------------------------+
| true   | me        | John   | comment.like    | Im sick of school                         |
+--------+-----------+--------+-----------------+-------------------------------------------+
| false  | me        | system | message         | The School is closed on independence day. |
+--------+-----------+--------+-----------------+-------------------------------------------+

Note: I don't recommend to group the notifications inside the database, do that on runtime this keeps things a lot more flexible.

  • Unread
    Every notification should have a flag to indicate if the recipient has already opened the notification.
  • Recipient
    Defines who receives the notification.
  • Sender
    Defines who triggered the notification.
  • Type
    Instead of having every Message in plain text inside your database create types. This way you can create special handlers for different notification types inside your backend. Will reduce the amount of data stored inside your database and gives your even more flexibility, enabled easy translating of notification, changes of past messages etc..
  • Reference
    Most notifications will have a Reference to a record on your database or your application.

Every system I have been working on had a simple 1 to 1 reference relationship on a notification, you might have an 1 to n keep in mind that I will continue my example with 1:1. This also means that I don't need a field defining what type of object is referenced because this is defined by the notification type.

SQL Table

Now when defining a real table structure for SQL we come to a few decisions in terms of the database design. I will go with simplest solution which will look something like this:

+--------------+--------+---------------------------------------------------------+
| column       | type   | description                                             |
+--------------+--------+---------------------------------------------------------+
| id           | int    | Primary key                                             |
+--------------+--------+---------------------------------------------------------+
| recipient_id | int    | The receivers user id.                                  |
+--------------+--------+---------------------------------------------------------+
| sender_id    | int    | The sender's user id.                                   |
+--------------+--------+---------------------------------------------------------+
| unread       | bool   | Flag if the recipient has already read the notification |
+--------------+--------+---------------------------------------------------------+
| type         | string | The notification type.                                  |
+--------------+--------+---------------------------------------------------------+
| parameters   | array  | Additional data to render different notification types. |
+--------------+--------+---------------------------------------------------------+
| reference_id | int    | The primary key of the referencing object.              |
+--------------+--------+---------------------------------------------------------+
| created_at   | int    | Timestamp of the notification creation date.            |
+--------------+--------+---------------------------------------------------------+

Or for the lazy folks the SQL create table command for this example:

CREATE TABLE `notifications` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `recipient_id` int(11) NOT NULL,
  `sender_id` int(11) NOT NULL,
  `unread` tinyint(1) NOT NULL DEFAULT '1',
  `type` varchar(255) NOT NULL DEFAULT '',
  `parameters` text NOT NULL,
  `reference_id` int(11) NOT NULL,
  `created_at` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

PHP Service

This implementation depends completely on the needs of your application, Note: This is an example not the golden standard on how to build an notification system in PHP.

Notification model

This is an example base model of the notification itself, nothing fancy just the needed properties and the abstract methods messageForNotification and messageForNotifications we expected being implemented in the different notification types.

abstract class Notification
{
    protected $recipient;
    protected $sender;
    protected $unread;
    protected $type;
    protected $parameters;
    protected $referenceId;
    protected $createdAt;

    /**
     * Message generators that have to be defined in subclasses
     */
    public function messageForNotification(Notification $notification) : string;
    public function messageForNotifications(array $notifications) : string;

    /**
     * Generate message of the current notification.
     */ 
    public function message() : string
    {
        return $this->messageForNotification($this);
    }
}

You will have to add a constructor, getters, setters and that kind of stuff by yourself in your own style, i'm not going to provide a ready to use Notification system.

Notification Types

Now you can create a new Notification subclass for every type. This following example would handle the like action of a comment:

  • Ray has liked your comment. (1 notification)
  • John and Jane liked your comment. (2 notifications)
  • Jane, Johnny, James and Jenny liked your comment. (4 notifications)
  • Jonny, James and 12 others liked your comment. (14 notifications)

Example implementation:

namespace Notification\Comment;

class CommentLikedNotification extends \Notification
{
    /**
     * Generate a message for a single notification
     * 
     * @param Notification              $notification
     * @return string 
     */
    public function messageForNotification(Notification $notification) : string 
    {
        return $this->sender->getName() . 'has liked your comment: ' . substr($this->reference->text, 0, 10) . '...'; 
    }

    /**
     * Generate a message for a multiple notifications
     * 
     * @param array              $notifications
     * @return string 
     */
    public function messageForNotifications(array $notifications, int $realCount = 0) : string 
    {
        if ($realCount === 0) {
            $realCount = count($notifications);
        }

        // when there are two 
        if ($realCount === 2) {
            $names = $this->messageForTwoNotifications($notifications);
        }
        // less than five
        elseif ($realCount < 5) {
            $names = $this->messageForManyNotifications($notifications);
        }
        // to many
        else {
            $names = $this->messageForManyManyNotifications($notifications, $realCount);
        }

        return $names . ' liked your comment: ' . substr($this->reference->text, 0, 10) . '...'; 
    }

    /**
     * Generate a message for two notifications
     *
     *      John and Jane has liked your comment.
     * 
     * @param array              $notifications
     * @return string 
     */
    protected function messageForTwoNotifications(array $notifications) : string 
    {
        list($first, $second) = $notifications;
        return $first->getName() . ' and ' . $second->getName(); // John and Jane
    }

    /**
     * Generate a message many notifications
     *
     *      Jane, Johnny, James and Jenny has liked your comment.
     * 
     * @param array              $notifications
     * @return string 
     */
    protected function messageForManyNotifications(array $notifications) : string 
    {
        $last = array_pop($notifications);

        foreach($notifications as $notification) {
            $names .= $notification->getName() . ', ';
        }

        return substr($names, 0, -2) . ' and ' . $last->getName(); // Jane, Johnny, James and Jenny
    }

    /**
     * Generate a message for many many notifications
     *
     *      Jonny, James and 12 other have liked your comment.
     * 
     * @param array              $notifications
     * @return string 
     */
    protected function messageForManyManyNotifications(array $notifications, int $realCount) : string 
    {
        list($first, $second) = array_slice($notifications, 0, 2);

        return $first->getName() . ', ' . $second->getName() . ' and ' .  $realCount . ' others'; // Jonny, James and 12 other
    }
}

Notification manager

To work with your notifications inside your application create something like a notification manager:

class NotificationManager
{
    protected $notificationAdapter;

    public function add(Notification $notification);

    public function markRead(array $notifications);

    public function get(User $user, $limit = 20, $offset = 0) : array;
}

The notificationAdapter property should contain the logic in direct communication with your data backend in the case of this example mysql.

Creating notifications

Using mysql triggers is not wrong, because there is no wrong solution. What works, works.. But I strongly recommend to not let the database handle application logic.

So inside the notification manager you might want to do something like this:

public function add(Notification $notification)
{
    // only save the notification if no possible duplicate is found.
    if (!$this->notificationAdapter->isDoublicate($notification))
    {
        $this->notificationAdapter->add([
            'recipient_id' => $notification->recipient->getId(),
            'sender_id' => $notification->sender->getId()
            'unread' => 1,
            'type' => $notification->type,
            'parameters' => $notification->parameters,
            'reference_id' => $notification->reference->getId(),
            'created_at' => time(),
        ]);
    }
}

Behind the add method of the notificationAdapter can be a raw mysql insert command. Using this adapter abstraction enables you to switch easily from mysql to a document based database like mongodb which would make sense for a Notification system.

The isDoublicate method on the notificationAdapter should simply check if there is already a notification with the same recipient, sender, type and reference.


I cannot point out enough that this is only a example. (Also I really have to shorten the next steps this post is getting ridiculously long -.-)


So assuming you have some kind of controller with an action when a teacher uploads homework:

function uploadHomeworkAction(Request $request)
{
    // handle the homework and have it stored in the var $homework.

    // how you handle your services is up to you...
    $notificationManager = new NotificationManager;

    foreach($homework->teacher->students as $student)
    {
        $notification = new Notification\Homework\HomeworkUploadedNotification;
        $notification->sender = $homework->teacher;
        $notification->recipient = $student;
        $notification->reference = $homework;

        // send the notification
        $notificationManager->add($notification);
    }
}

Will create a notification for every teacher's student when he uploads a new homework.

Reading the notifications

Now comes the hard part. The problem with grouping on the PHP side is that you will have to load all notifications of the current user to group them correctly. This would be bad, well if you have only a few users it would probably still be no problem, but that doesn't make it good.

The easy solution is to simply limit the number of notifications requested and only grouping these. This will work fine when there are not many similar notifications (like 3-4 per 20). But lets say the post of a user / student gets about a hundred likes and you only select the last 20 notifications. The user will then only see that 20 people liked his post also that would be his only notification.

A "correct" solution would be grouping the notifications already on the database and selecting only some samples per notification group. Than you would just have to inject the real count into your notification messages.

You probably didn't read the text below so let me continue with a snippet:

select *, count(*) as count from notifications
where recipient_id = 1
group by `type`, `reference_id`
order by created_at desc, unread desc
limit 20

Now you know what notifications should be around for the given user and how many notifications the group contains.

And now the shitty part. I still could not find out a better way to select a limited number of notifications for each group without doing a query for every group. All suggestions here are very welcome.

So I do something like:

$notifcationGroups = [];

foreach($results as $notification)
{
    $notifcationGroup = ['count' => $notification['count']];

    // when the group only contains one item we don't 
    // have to select it's children
    if ($notification['count'] == 1)
    {
        $notifcationGroup['items'] = [$notification];
    }
    else
    {
        // example with query builder
        $notifcationGroup['items'] = $this->select('notifications')
            ->where('recipient_id', $recipient_id)
            ->andWehere('type', $notification['type'])
            ->andWhere('reference_id', $notification['reference_id'])
            ->limit(5);
    }

    $notifcationGroups[] = $notifcationGroup;
}

I will now continue assuming that the notificationAdapters get method implements this grouping and returns an array like this:

[
    {
        count: 12,
        items: [Note1, Note2, Note3, Note4, Note5] 
    },
    {
        count: 1,
        items: [Note1] 
    },
    {
        count: 3,
        items: [Note1, Note2, Note3] 
    }
]

Because we always have at least one notification in our group and our ordering prefers Unread and New notifications we can just use the first notification as a sample for rendering.

So to be able to work with these grouped notifications we need a new object:

class NotificationGroup
{
    protected $notifications;

    protected $realCount;

    public function __construct(array $notifications, int $count)
    {
        $this->notifications = $notifications;
        $this->realCount = $count;
    }

    public function message()
    {
        return $this->notifications[0]->messageForNotifications($this->notifications, $this->realCount);
    }

    // forward all other calls to the first notification
    public function __call($method, $arguments)
    {
        return call_user_func_array([$this->notifications[0], $method], $arguments);
    }
}

And finally we can actually put most of the stuff together. This is how the get function on the NotificationManager might look like:

public function get(User $user, $limit = 20, $offset = 0) : array
{
    $groups = [];

    foreach($this->notificationAdapter->get($user->getId(), $limit, $offset) as $group)
    {
        $groups[] = new NotificationGroup($group['notifications'], $group['count']);
    }

    return $gorups;
}

And really finally inside a possible controller action:

public function viewNotificationsAction(Request $request)
{
    $notificationManager = new NotificationManager;

    foreach($notifications = $notificationManager->get($this->getUser()) as $group)
    {
        echo $group->unread . ' | ' . $group->message() . ' - ' . $group->createdAt() . "\n"; 
    }

    // mark them as read 
    $notificationManager->markRead($notifications);
}
2 of 4
2

Answer:

  1. Introduce a read/unread variable on the notification. You can then pull only unread notifications by doing ... WHERE status = 'UNREAD' in your sql.

  2. You can't really... you will want to push that notification. What you can do is still aggregate them though by using GROUP BY. You would likely want to group on something unique like a new homework so it might be something like ... GROUP BY homework.id

Discussions

Simple free solutions for PHP to send notifications to my phone besides SMS and email?
Use something like sentry.io. You can also use a push notification api, but using a Telegram client is very simple - create a group, add a bot (though botfather) and send the message with the group id with the bot access keys. More on reddit.com
🌐 r/webdev
21
2
March 12, 2023
Web push notifications with PHP and Javascript
Do not listen about web sockets. Web push notifications are not web sockets at all. https://www.w3.org/TR/push-api/#h-sequence-diagram I've done it in ruby, but there is same libraries for php and nodejs - interface, actually, almost similar. PHP: https://github.com/web-push-libs/web-push-php Nodejs: https://www.npmjs.com/package/web-push Ruby: https://github.com/zaru/webpush Also, you could use something like onesignal.com, but I will tell about how to do by yourself. There is an brief example how it works: Web push requires server part to encrypt and send messages (this is library for). You can do it via cron, daemon, jobs or like you whatever. When you want to send notification, you should send it to stored before endpoint url. This endpoint url is related to browser vendor. For now it's firefox and google chrome (android firefox works also). This endpoint url you will receive via JS-code when person will subscribe - you need simple js code for this. When browser starts, vendor will send notification to it. Browser will catch this with service-worker - it's js-script which works like a daemon but within browser. It does not require opened tab. So, you should write your own service worker which will handle push event to show it. It requires HTTPS and manifest.json file. I can give you an example of my app (it's on ruby, but simple). Server side: https://github.com/violarium/ruby_moon/blob/master/app/services/notification_sender/webpush_sender.rb#L28-L32 Client side (service worker): https://github.com/violarium/ruby_moon/blob/master/public/serviceworker.js#L48-L61 Client side (subscription for web push): https://github.com/violarium/ruby_moon/blob/master/app/assets/javascripts/serviceworker-companion.js#L5-L12 My manifest.json: https://github.com/violarium/ruby_moon/blob/master/public/manifest.json Materials which I've used and which could help you: Google have good documentation for client: https://developers.google.com/web/fundamentals/engage-and-retain/push-notifications/ About service workers: https://developers.google.com/web/fundamentals/getting-started/primers/service-workers This is blog for full integration: https://rossta.net/blog/web-push-notifications-from-rails.html Some tips, which I've discovered: Google Chrome does not need gcm registration anymore Web push can send only plain text, but you can send json and decode it on client (within service worker) You can define how notifications will work in service worker right right away or you can make flexible notifications according to received data You can debug service workers with google chrome Do not digest service worker file with anything like service-worker-12387623487234.js - browser has own mechanism to update it, also it just could register 2 and more service workers for one site. If you really can't do it on php, you could write simple script on ruby or nodejs to call them to send notifications. More on reddit.com
🌐 r/PHP
19
16
February 10, 2017
People also ask

How do I create a notification system in PHP?
Create a database table to store notifications, develop forms and navigation to manage them, insert notifications as needed, and implement methods to fetch and display notifications to users.
🌐
cloudways.com
cloudways.com › home › creating real time notification system in php and ajax polling
Create Real Time Notification System in PHP with Ajax
How do I send push notifications using PHP?
Use a push notification service with an API, then use PHP to send the required data to deliver notifications and handle API responses appropriately.
🌐
cloudways.com
cloudways.com › home › creating real time notification system in php and ajax polling
Create Real Time Notification System in PHP with Ajax
How can I implement real-time notifications in PHP?
Set up your backend to handle events that trigger notifications, integrate a push notification service, implement frontend display, allow user preferences, and test for reliability and performance.
🌐
cloudways.com
cloudways.com › home › creating real time notification system in php and ajax polling
Create Real Time Notification System in PHP with Ajax
🌐
Phppot
phppot.com › php › facebook-like-header-notification-in-php
Facebook Like Header Notification in PHP - Phppot
<script type="text/javascript"> function myFunction() { $.ajax({ url: "view_notification.php", type: "POST", processData:false, success: function(data){ $("#notification-count").remove(); $("#notification-latest").show();$("#notification-latest").html(data); }, error: function(){} }); } $(document).ready(function() { $('body').click(function(e){ if ( e.target.id != 'notification-icon'){ $("#notification-latest").hide(); } }); }); </script> ... Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science.
🌐
PHPpot
phppot.com › php › web-push-notifications-php
Web Push Notifications in PHP - PHPpot
If you want a fully PHP solution to send custom notifications, the linked article will be useful. This example shows a web push notification on the browser. The notifications are sent every 10 minutes as configured. Then, the sent notifications are closed automatically. The notifications display time on a browser is configured as 5 minutes. The notification instances are created and handled on the client side.
🌐
Phpzag
phpzag.com › push-notification-system-with-php-mysql
Push Notification System with PHP & MySQL – PHPZAG.COM
July 5, 2023 - As we will cover this tutorial ... is following. ... Step1: Create Database Tables First we will create MySQL database table notif_user to store users for login to show notification message to logged in users....
🌐
Gravitec
gravitec.net › home › web push notifications › web push notifications in php – a complete guide
Setting Up Push Notifications in PHP: A Complete Guide - Blog Gravitec.net
March 31, 2025 - Learn how to implement push notifications in PHP. Set up Service Workers, integrate with FCM, send messages, and automate push marketing for better user engagement.
Find elsewhere
🌐
WD
webdamn.com › home › tutorials › php › build push notification system with php & mysql
Build Push Notification System with PHP & MySQL | WD
May 12, 2024 - We will handle user login functionality by calling login() method from User.php class. We will store username into session to use while implementing push notification functionality. session_start(); $message = ''; if (!empty($_POST['username']) && !empty($_POST['password'])) { include_once 'config/Database.php'; include_once 'class/User.php'; $database = new Database(); $db = $database->getConnection(); $user = new User($db); $user->username = $_POST['username']; $user->password = $_POST['password']; if($user->login()) { $_SESSION['username'] = $user->username; header("Location:index.php"); } else { $message = "Invalid username or password!"; } }
🌐
Laravel
laravel.com › docs › 11.x › notifications
Notifications - Laravel 11.x - The PHP Framework For Web ...
Notifications may be sent in two ways: using the notify method of the Notifiable trait or using the Notification facade. The Notifiable trait is included on your application's App\Models\User model by default: ... <?php namespace App\Models; ...
🌐
Laravel
laravel.com › docs › 12.x › notifications
Notifications | Laravel 12.x - The clean stack for Artisans and agents
Notifications may be sent in two ways: using the notify method of the Notifiable trait or using the Notification facade. The Notifiable trait is included on your application's App\Models\User model by default: ... <?php namespace App\Models; ...
🌐
Nativephp
nativephp.com › docs › desktop › 1 › the-basics › notifications
Notifications - NativePHP desktop v1 - NativePHP
... You may send a notification using the Notification facade. ... Notification::title('Hello from NativePHP') ->message('This is a detail message coming from your Laravel app.') ->show();
🌐
GitHub
github.com › KajalBhammar › Notification-System-using-PHP
GitHub - KajalBhammar/Notification-System-using-PHP: This project implements a real-time notification system using PHP, AJAX, Bootstrap, and MySQL. It allows users to receive notifications instantly and view them in a dropdown menu on the navigation bar.
This project implements a real-time notification system using PHP, AJAX, Bootstrap, and MySQL. It allows users to receive notifications instantly and view them in a dropdown menu on the navigation ...
Author   KajalBhammar
🌐
PHP Classes
phpclasses.org › blog › package › 11632 › post › 1-How-to-Use-PHP-to-Send-Web-Push-Notifications-for-Your-Web-Site-in-2020.html
How to Use a PHP Push Notifications Class on Your Web Site in 2023 with this Send Web Push Notifications Tutorial - PHP Web Push Notifications Server package blog - PHP Classes
November 23, 2023 - The user client must first subscribe to the notifications and then receive and display them. On the client side, JavaScript is used for this. The standard web push API is implemented in almost all popular desktop and mobile browsers. Subscriptions must be saved and managed on the server side and the desired messages sent. In this tutorial, the server side is implemented with PHP...
🌐
PHP
php.net › manual › en › function.pg-get-notify.php
PHP: pg_get_notify - Manual
<?php $conn = pg_pconnect("dbname=publisher"); if (!$conn) { echo "An error occurred.\n"; exit; } // Listen 'author_updated' message from other processes pg_query($conn, 'LISTEN author_updated;'); $notify = pg_get_notify($conn); if (!$notify) { echo "No messages\n"; } else { print_r($notify); } ?> ... Instant yet Simple PHP notification with HTML5 Server-Sent Events sse.php <?php $dbconn = new PDO("pgsql:host=localhost;dbname=mydb", "pduser", "userpass"); $dbconn->exec('LISTEN "channel_name"'); // those doublequotes are very important header("X-Accel-Buffering: no"); // disable ngnix webServer
🌐
Voxfor
voxfor.com › blog › how to build a real-time php notification system with mysql and ajax
How to Build a Real-Time PHP Notification System with MySQL and AJAX
June 12, 2025 - We could use this message for debugging or logging.) Finally, we close the database connection with mysqli_close($con). At this stage, when the user submits the form, this insert.php will run (we’ll wire it up via AJAX in a later step), and a new row will be added to the comments table. Every new comment is initially marked as comment_status = 0 (unseen). Next, we need to fetch these unseen comments and send them to the front end as notifications.
🌐
Scaler
scaler.com › home › topics › php alert
PHP alert - Scaler Topics
April 1, 2024 - While PHP itself does not have ... client side. By generating JavaScript code within a PHP script, developers can trigger alert boxes and convey important messages to users interacting with web applications....
🌐
Source Code Tester
sourcecodester.com › tutorial › php › 15965 › dynamic-web-notification-using-php-and-javascript-tutorial
Dynamic Web Notification using PHP and JavaScript Tutorial | SourceCodester
December 14, 2022 - It is a PHP script that updates the notification details as sent after the web push notification is created. ... Lastly, the following snippet is a JavaScript file known as script.js.
🌐
Nomad PHP
nomadphp.com › blog › 72 › implement-web-push-notification-in-php-using-w3c-provided-notification-api
Implement Web Push Notification in PHP using W3C provided Notification API
<?php require 'db_connect.php'; ?> <!DOCTYPE html> <html> <head> <title>ADMIN PAGE</title> <link href=" <script src=" <script src=" <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous"> <?php if(isset($_POST['login'])) { $_SESSION['admin_login']=0; $username=$conn->real_escape_string($_POST['username']); $password=$conn->real_escape_string($_POST['password']); $sql = "SELECT * FROM admin where username='".$username."' and password='".md5($password)."' ";
🌐
Reintech
reintech.io › blog › implementing-real-time-notifications-php-applications-pusher
Implementing Real-time Notifications in PHP Applications with Pusher | Reintech media
January 7, 2026 - In this tutorial, learn how to implement real-time notifications in PHP applications using the Pusher service. Enhance your web applications with real-time functionality and improve user experience.