Creating a Notification System in CodeIgniter 3
Here's a comprehensive guide to implementing a notification system in CodeIgniter 3 for your school approval workflow:
1. Database Setup
First, create a notifications table:
CREATE TABLE `notifications` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL COMMENT 'ID of the user who should receive the notification',
`type` varchar(50) NOT NULL COMMENT 'Type of notification (e.g., school_request, school_approved)',
`title` varchar(255) NOT NULL,
`message` text NOT NULL,
`is_read` tinyint(1) DEFAULT 0,
`created_at` datetime NOT NULL,
`read_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2. Notification Model
Create a model to handle notifications:
// application/models/Notification_model.php
class Notification_model extends CI_Model {
public function __construct() {
parent::__construct();
$this->load->database();
}
// Create a new notification
public function create($user_id, $type, $title, $message) {
$data = array(
'user_id' => $user_id,
'type' => $type,
'title' => $title,
'message' => $message,
'is_read' => 0,
'created_at' => date('Y-m-d H:i:s')
);
return $this->db->insert('notifications', $data);
}
// Get unread notifications for a user
public function get_unread($user_id) {
$this->db->where('user_id', $user_id);
$this->db->where('is_read', 0);
$this->db->order_by('created_at', 'DESC');
return $this->db->get('notifications')->result();
}
// Get all notifications for a user
public function get_all($user_id) {
$this->db->where('user_id', $user_id);
$this->db->order_by('created_at', 'DESC');
return $this->db->get('notifications')->result();
}
// Mark notification as read
public function mark_as_read($id) {
$this->db->where('id', $id);
$this->db->update('notifications', array(
'is_read' => 1,
'read_at' => date('Y-m-d H:i:s')
));
}
// Mark all notifications as read for a user
public function mark_all_as_read($user_id) {
$this->db->where('user_id', $user_id);
$this->db->update('notifications', array(
'is_read' => 1,
'read_at' => date('Y-m-d H:i:s')
));
}
// Count unread notifications
public function count_unread($user_id) {
$this->db->where('user_id', $user_id);
$this->db->where('is_read', 0);
return $this->db->count_all_results('notifications');
}
}
3. Notification Helper
Create a helper for easy notification creation:
// application/helpers/notification_helper.php
if (!defined('BASEPATH')) exit('No direct script access allowed');
if (!function_exists('create_notification')) {
function create_notification($user_id, $type, $title, $message) {
$CI =& get_instance();
$CI->load->model('notification_model');
return $CI->notification_model->create($user_id, $type, $title, $message);
}
}
4. Notification Library
Create a library for more advanced notification features:
// application/libraries/Notification.php
class Notification {
protected $ci;
public function __construct() {
$this->ci =& get_instance();
$this->ci->load->model('notification_model');
}
// Create a notification
public function create($user_id, $type, $title, $message) {
return $this->ci->notification_model->create($user_id, $type, $title, $message);
}
// Create a system-wide notification (for all users)
public function create_system($type, $title, $message) {
$users = $this->ci->db->get('users')->result();
foreach ($users as $user) {
$this->create($user->id, $type, $title, $message);
}
}
// Get notifications for a user
public function get($user_id, $unread_only = false) {
if ($unread_only) {
return $this->ci->notification_model->get_unread($user_id);
}
return $this->ci->notification_model->get_all($user_id);
}
// Mark notification as read
public function mark_as_read($id) {
return $this->ci->notification_model->mark_as_read($id);
}
// Mark all notifications as read
public function mark_all_as_read($user_id) {
return $this->ci->notification_model->mark_all_as_read($user_id);
}
// Count unread notifications
public function count_unread($user_id) {
return $this->ci->notification_model->count_unread($user_id);
}
}
5. Implementing Notifications in Your Workflow
When a rep creates a school request:
// In your Schools controller's create_request method
if ($this->db->insert('school_requests', $data)) {
// Create notification for admin
$admin_id = $this->get_admin_id(); // You need to implement this
create_notification(
$admin_id,
'school_request',
'New School Request',
'A new school request has been submitted by a rep and needs your approval.'
);
// Or using the library:
// $this->notification->create($admin_id, 'school_request', 'New School Request', '...');
}
When an admin approves a school request:
// In your Schools controller's approve_request method
if ($this->approve_school($request_id)) {
// Get the rep who created the request
$rep_id = $this->get_rep_id_for_request($request_id); // Implement this
// Create notification for rep
create_notification(
$rep_id,
'school_approved',
'School Approved',
'Your school request has been approved and is now live in the system.'
);
}
6. Displaying Notifications in Views
Create a notification dropdown in your header:
// application/views/templates/header.php
<div class="dropdown notifications-dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-bell"></i>
<span class="badge"><?php echo $unread_count; ?></span>
</a>
<ul class="dropdown-menu">
<li class="dropdown-header">Notifications</li>
<?php if (empty($notifications)): ?>
<li><a href="#">No notifications</a></li>
<?php else: ?>
<?php foreach ($notifications as $notification): ?>
<li>
<a href="<?php echo site_url('notifications/view/' . $notification->id); ?>">
<strong><?php echo $notification->title; ?></strong><br>
<small><?php echo $notification->message; ?></small>
</a>
</li>
<?php endforeach; ?>
<li class="divider"></li>
<li><a href="<?php echo site_url('notifications/mark_all_as_read'); ?>">Mark all as read</a></li>
<?php endif; ?>
</ul>
</div>
7. Notification Controller
Create a controller to handle notification actions:
// application/controllers/Notifications.php
class Notifications extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('notification_model');
$this->load->library('notification');
}
// View a single notification
public function view($id) {
$notification = $this->notification_model->get_notification($id);
if ($notification && $notification->user_id == $this->ion_auth->user()->row()->id) {
$this->notification_model->mark_as_read($id);
// Display the notification
} else {
show_error('Notification not found or unauthorized access');
}
}
// Mark all notifications as read
public function mark_all_as_read() {
$this->notification->mark_all_as_read($this->ion_auth->user()->row()->id);
redirect($_SERVER['HTTP_REFERER']);
}
// Get notifications via AJAX
public function get_notifications() {
$notifications = $this->notification->get($this->ion_auth->user()->row()->id, true);
$this->output
->set_content_type('application/json')
->set_output(json_encode($notifications));
}
}
8. AJAX Implementation
Add this to your JavaScript to update notifications without page refresh:
// Check for new notifications periodically
function checkNotifications() {
$.ajax({
url: base_url + 'notifications/get_notifications',
type: 'GET',
success: function(data) {
// Update your notification dropdown with the new data
updateNotificationDropdown(data);
}
});
}
// Call this function every 30 seconds
setInterval(checkNotifications, 30000);
// Initial check
$(document).ready(function() {
checkNotifications();
});
9. Additional Features to Consider
- Email Notifications: Integrate with a service like Mandrill or SendGrid to send email notifications.
- Web Push Notifications: For browser notifications when users are active.
- Notification Preferences: Allow users to customize which notifications they receive.
- Notification Categories: Organize notifications by type (schools, messages, etc.).
- Pagination: For users with many notifications.
This implementation provides a solid foundation for your notification system in CodeIgniter 3. You can extend it based on your specific requirements.