devsfort / laravel-pigeon-chat
A Laravel package that allows you to add a complete user messaging system into your new/existing Laravel application with only a few easy steps..
Requires
- php: >=7.4
- laravel/framework: >=8.0
README
# Laravel Pigeon ChatA highly customizable Laravel package that provides a complete real-time chat system with individual messaging, group chat, and extensive customization capabilities. Built with modern technologies including Socket.IO, Redis, and Laravel's broadcasting system.
๐ Table of Contents
- ๐ Features
- ๐ Requirements
- ๐ Installation
- โ๏ธ Configuration
- ๐ฏ Quick Start
- ๐ง Customization
- ๐ Architecture
- ๐ Database Schema
- ๐ Real-time Features
- ๐ Security Features
- ๐ Performance & Scalability
- ๐งช Testing
- ๐ง Troubleshooting
- ๐ Documentation
- ๐ค Contributing
- ๐ License
- ๐จโ๐ป Author
- ๐ Acknowledgments
- ๐ Changelog
- ๐ Support
๐ Features
Core Chat Functionality
- โ Individual User Chat - One-to-one messaging between users
- โ Group Chat - Multi-user group conversations with admin controls
- โ Real-time Messaging - Instant message delivery using Socket.IO
- โ File Attachments - Support for images, documents, and other files
- โ Message Status - Read receipts and delivery confirmations
- โ Typing Indicators - Real-time typing notifications
- โ User Status - Online/offline status tracking
- โ Search & Favorites - Message search and favorite conversations
- โ Dark/Light Mode - User preference themes
- โ Responsive Design - Mobile-friendly chat interface
Advanced Features
- โ Channel-Based Broadcasting - Separate channels for user and group chats
- โ Room Management - Efficient Socket.IO room handling
- โ Permission System - Granular control over user actions
- โ Content Moderation - Customizable message validation
- โ Caching System - Configurable caching for performance
- โ API Support - RESTful API endpoints with rate limiting
- โ Notification System - Multi-channel notifications
- โ Database Optimization - Efficient queries and relationships
Customization & Extensibility
- โ Complete Override System - Override any aspect of the package
- โ Custom User Logic - Custom user filtering and permissions
- โ Custom Message Logic - Custom validation and filtering
- โ Custom Group Logic - Custom group creation and management
- โ Custom Events - Custom broadcasting and event handling
- โ Custom Services - Extensible service layer architecture
- โ Custom Controllers - Extend and customize controllers
- โ Custom Views - Complete UI customization
- โ Custom Routes - Custom routing and middleware
- โ Custom Database - Custom migrations and connections
๐ Requirements
- PHP: >= 7.4
- Laravel: >= 8.0
- Node.js: >= 14.0 (for Socket.IO server)
- Redis: For broadcasting and caching
- Database: MySQL, PostgreSQL, or SQLite
๐ Installation
1. Install Package via Composer
composer require devsfort/laravel-pigeon-chat
2. Publish Configuration and Assets
# Publish configuration php artisan vendor:publish --tag=devschat-config # Publish migrations php artisan vendor:publish --tag=devschat-migrations # Publish views (optional) php artisan vendor:publish --tag=devschat-views # Publish controllers (optional) php artisan vendor:publish --tag=devschat-controllers # Publish assets php artisan vendor:publish --tag=devschat-assets # Publish Node.js server file php artisan vendor:publish --tag=devschat-server
3. Run Migrations
php artisan migrate
โ ๏ธ Important for Fresh Laravel Installations: If you're installing this package in a fresh Laravel application (especially with Jetstream), you might encounter foreign key constraint errors. The package now handles this automatically, but if you still get errors, see the Troubleshooting section below.
4. Install Node.js Dependencies
# Install dependencies for Socket.IO server npm install express socket.io ioredis # Or use the provided package.json cp package-chat.json package.json npm install
5. Configure Broadcasting
Update your .env
file:
BROADCAST_DRIVER=redis REDIS_HOST=127.0.0.1 REDIS_PORT=6379 REDIS_DB=0
6. Start Socket.IO Server
# Start the chat server
node server.js
โ๏ธ Configuration
Environment Variables
The package is highly configurable through environment variables:
# Basic Configuration DEVSFORT_NAME="Your Chat App Name" DEVSFORT_PATH="chat" DEVSFORT_MIDDLEWARE="auth" # Socket Configuration SOCKET_HOST="127.0.0.1" SOCKET_PORT="8005" # Redis Configuration REDIS_CLIENT="predis" REDIS_HOST="127.0.0.1" REDIS_PORT="6379" REDIS_DB="0" # File Upload Configuration DEVSFORT_ATTACHMENTS_FOLDER="chat-attachments" DEVSFORT_ATTACHMENTS_MAX_SIZE="150000000" DEVSFORT_ALLOWED_IMAGES="png,jpg,jpeg,gif" DEVSFORT_ALLOWED_FILES="zip,rar,txt,pdf" # Avatar Configuration DEVSFORT_USER_AVATAR_FOLDER="user-avatars" DEVSFORT_USER_AVATAR_DEFAULT="default-avatar.png" DEVSFORT_GROUP_AVATAR_FOLDER="group-avatars" DEVSFORT_GROUP_AVATAR_DEFAULT="default-group.png" # Group Configuration DEVSFORT_GROUPS_MAX_MEMBERS="100" DEVSFORT_GROUPS_ALLOW_PRIVATE="true" DEVSFORT_GROUPS_ALLOW_REMOVAL="true" DEVSFORT_GROUPS_ALLOW_PROMOTION="true" # Cache Configuration DEVSFORT_CACHE_ENABLED="true" DEVSFORT_CACHE_DRIVER="redis" DEVSFORT_CACHE_PREFIX="chat" DEVSFORT_CACHE_TTL="3600" # API Configuration DEVSFORT_API_ENABLED="true" DEVSFORT_API_VERSION="v1" DEVSFORT_API_RATE_LIMIT="60"
Customization Configuration
For advanced customization, see the Customization Guide:
# User Customization DEVSFORT_USER_MODEL="App\Models\CustomUser" DEVSFORT_USER_SCOPE="App\Services\CustomUserScope" DEVSFORT_USER_SERVICE="App\Services\CustomUserService" # Message Customization DEVSFORT_MESSAGE_VALIDATOR="App\Validators\CustomMessageValidator" DEVSFORT_MESSAGE_FILTER="App\Filters\CustomMessageFilter" # Group Customization DEVSFORT_GROUP_VALIDATOR="App\Validators\CustomGroupValidator" DEVSFORT_GROUP_PERMISSION_HANDLER="App\Handlers\CustomGroupPermissionHandler" # Service Customization DEVSFORT_CHAT_SERVICE="App\Services\CustomChatService" DEVSFORT_GROUP_SERVICE="App\Services\CustomGroupService" # Controller Customization DEVSFORT_MESSAGES_CONTROLLER="App\Http\Controllers\CustomMessagesController" # View Customization DEVSFORT_VIEW_LAYOUT="layouts.custom-chat" DEVSFORT_VIEW_CHAT="pages.custom-chat" # Route Customization DEVSFORT_CUSTOM_ROUTES="routes/custom-chat.php" DEVSFORT_MIDDLEWARE_CUSTOM='["custom.chat","throttle:60,1"]'
๐ฏ Quick Start
Basic Usage
-
Access Chat Interface
http://your-app.com/chat
-
Send Messages
- Click on any user to start a conversation
- Type your message and press Enter
- Attach files by clicking the attachment button
-
Create Groups
- Click on the "Groups" tab
- Click "Create Group"
- Add members and set group settings
API Usage
// Send a message $response = Http::post('/chat/sendMessage', [ 'id' => $userId, 'message' => 'Hello!', 'type' => 'user' ]); // Create a group $response = Http::post('/chat/createGroup', [ 'name' => 'My Group', 'description' => 'Group description', 'members' => [1, 2, 3], 'is_private' => false ]);
๐ง Customization
Why Customize?
The package is designed to be highly customizable because:
- Business Logic: Every application has unique requirements
- User Management: Different user models and permission systems
- Content Rules: Custom validation and moderation needs
- Integration: Must work with existing systems
- Scalability: Adapt to growing application needs
Customization Methods
1. Environment Variables (Simple)
# Override basic settings DEVSFORT_USER_MODEL="App\Models\CustomUser" DEVSFORT_MESSAGE_VALIDATOR="App\Validators\CustomValidator"
2. Class Extension (Recommended)
<?php namespace App\Services; use DevsFort\Pigeon\Chat\Library\BaseChatService; class CustomChatService extends BaseChatService { public function getUsersForChat($excludeCurrentUser = true) { $query = parent::getUsersForChat($excludeCurrentUser); // Add custom logic $query->where('company_id', auth()->user()->company_id); $query->where('active_status', 1); return $query->get(); } }
3. Interface Implementation (Advanced)
<?php namespace App\Validators; class CustomMessageValidator { public function validate($data) { // Custom validation logic return ['valid' => true, 'errors' => []]; } }
Customization Examples
See the Examples Directory for complete implementation examples:
CustomUserScope.php
- User filtering examplesCustomUserService.php
- User service examplesCustomMessageValidator.php
- Message validation examplesCustomGroupValidator.php
- Group validation examples
Complete Customization Guide
For comprehensive customization information, see:
- ๐ Customization Guide - Complete step-by-step guide with examples
- ๐ Customization Summary - Overview of all customization features
- ๐ก Examples Directory - Ready-to-use customization examples
๐ก Pro Tip: Start with the Customization Summary for an overview, then dive into the Customization Guide for detailed implementation steps.
๐ Architecture
Package Structure
src/
โโโ ChatServiceProvider.php # Service provider
โโโ config/
โ โโโ devschat.php # Configuration file
โโโ database/
โ โโโ migrations/ # Database migrations
โโโ Events/ # Broadcasting events
โโโ Facade/
โ โโโ Chat.php # Facade for easy access
โโโ Http/
โ โโโ Controllers/ # Controllers
โโโ Library/
โ โโโ BaseChatService.php # Extensible base service
โ โโโ DevsFortChat.php # Default implementation
โโโ Models/ # Eloquent models
โโโ routes/
โ โโโ web.php # Route definitions
โโโ views/ # Blade templates
โโโ assets/ # CSS, JS, images
Key Components
BaseChatService
- Extensible service layerPrivateMessageEvent
- Broadcasting eventsMessagesController
- Main controllerGroup
&GroupMember
- Group management models- Socket.IO Server - Real-time communication
๐ Database Schema
Core Tables
users
- User information and preferencesmessages
- Chat messages with attachmentsfavorites
- Favorite conversationsgroups
- Group informationgroup_members
- Group membership and roles
Relationships
// User can have many messages User -> hasMany(Message) // Group has many members Group -> belongsToMany(User, 'group_members') // Message belongs to sender and receiver Message -> belongsTo(User, 'from_id') Message -> belongsTo(User, 'to_id')
๐ Real-time Features
Socket.IO Implementation
- Channel-Based Broadcasting - Separate channels for different message types
- Room Management - Efficient user and group room handling
- Redis Integration - Scalable broadcasting across multiple servers
- Event Handling - Customizable event processing
Supported Events
user-chat
- Individual user messagesgroup-chat
- Group chat messagesuser-status
- User online/offline statustyping-indicators
- Real-time typing notificationsmessage-seen
- Message read confirmations
๐ Security Features
Built-in Security
- Authentication Required - All routes protected by auth middleware
- Permission Checking - User action validation
- Content Validation - Message content filtering
- File Upload Security - File type and size validation
- CSRF Protection - Laravel's built-in CSRF protection
Custom Security
- Custom Permission Handlers - Implement your own permission logic
- Custom Validators - Add custom validation rules
- Custom Middleware - Add custom security middleware
- Role-Based Access - Integrate with existing role systems
๐ Performance & Scalability
Performance Features
- Caching System - Configurable Redis caching
- Database Optimization - Efficient queries and relationships
- Asset Optimization - Minified CSS and JavaScript
- Lazy Loading - On-demand data loading
Scalability Features
- Horizontal Scaling - Multiple Socket.IO instances
- Redis Clustering - Support for Redis clusters
- Load Balancing - Distribute connections across servers
- Database Sharding - Support for database sharding
๐งช Testing
Testing the Package
# Test basic functionality php artisan serve # Visit: http://localhost:8000/chat # Test Socket.IO server node server.js # Server should start on port 8005 # Test Redis connection redis-cli ping # Should return: PONG
Custom Testing
<?php namespace Tests; use DevsFort\Pigeon\Chat\Library\DevsFortChat; class ChatTest extends TestCase { public function test_custom_user_service() { $chatService = new CustomChatService(); $users = $chatService->getUsersForChat(); $this->assertNotEmpty($users); } }
๐ง Troubleshooting
Common Issues
-
Migration Errors (Foreign Key Constraints)
- Error:
SQLSTATE[HY000]: General error: 1005 Can't create table 'groups' (errno: 150 "Foreign key constraint is incorrectly formed")
- Solution: This happens in fresh Laravel installations. The package now handles this automatically by checking if tables exist before adding foreign keys.
- Alternative: If you still get errors, run migrations in this order:
php artisan migrate:fresh # Then install the package composer require devsfort/laravel-pigeon-chat php artisan vendor:publish --tag=devschat-migrations php artisan migrate
- Error:
-
Messages Not Sending
- Check Redis connection
- Verify Socket.IO server is running
- Check broadcasting configuration
-
Users Not Loading
- Verify user model configuration
- Check custom user scope implementation
- Verify database relationships
-
Group Creation Fails
- Check group validation rules
- Verify custom group validator
- Check database permissions
-
Real-time Not Working
- Verify Socket.IO server is running
- Check Redis configuration
- Verify event broadcasting
Debug Mode
# Enable debug mode APP_DEBUG=true # Check logs tail -f storage/logs/laravel.log # Check Redis redis-cli monitor # Check Socket.IO # Monitor server.js console output
๐ Documentation
Available Documentation
- README.md - This file (overview and quick start)
- CUSTOMIZATION_GUIDE.md - Complete customization guide
- CUSTOMIZATION_SUMMARY.md - Customization features overview
- Examples Directory - Ready-to-use customization examples
Documentation Structure
- README.md - Package overview and quick start
- Customization Guide - Step-by-step customization instructions
- Examples - Working code examples for all customization points
- Configuration Reference - Complete configuration options
๐ค Contributing
How to Contribute
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
Development Setup
# Clone repository git clone https://github.com/your-username/laravel-pigeon-chat.git # Install dependencies composer install npm install # Run tests php artisan test # Build assets npm run build
๐ License
This package is open-sourced software licensed under the MIT license.
๐จโ๐ป Author
Haseeb Ahmad - haseeb@devsfort.com
Professional Profile
- CEO & Founder @ Devsfort
- Technical Team Lead @ Softversum Dubai
- Senior Consultant @ 9t5 Private Limited Lahore
- AWS Certified Professional
Contact & Links
- Website: https://haseebahmad.com
- Email: haseeb@devsfort.com
- Company: Devsfort
๐ Acknowledgments
- Laravel team for the amazing framework
- Socket.IO team for real-time communication
- Redis team for fast data storage
- All contributors and users of this package
๐ Changelog
Version 2.0.0 (Latest)
- โจ Complete Customization System - Override any aspect of the package
- โจ Group Chat Support - Full group messaging functionality
- โจ Channel-Based Broadcasting - Separate channels for different message types
- โจ Extensible Service Layer - Base service class for customization
- โจ Advanced Configuration - 50+ configuration options
- โจ Comprehensive Documentation - Complete customization guides
- โจ Example Implementations - Ready-to-use customization examples
Version 1.0.0
- โจ Basic Chat Functionality - Individual user messaging
- โจ Real-time Communication - Socket.IO integration
- โจ File Attachments - Support for various file types
- โจ User Management - Basic user functionality
๐ Support
Getting Help
- Documentation: Check the customization guides first
- Examples: Review the example implementations
- Issues: Report bugs on GitHub
- Discussions: Ask questions in GitHub discussions
Support Channels
- GitHub Issues: Report bugs and request features
- GitHub Discussions: Ask questions and share solutions
- Email: haseeb@devsfort.com
โญ Star this repository if you find it helpful!
๐ง Need customization help? Check the Customization Guide for comprehensive examples and instructions.
๐ Ready to get started? Follow the installation steps above and begin building your custom chat solution!