Skip to content

πŸ’¬ Real-time chat application built with Laravel & Socket.IO. Features WhatsApp-like UI, instant messaging, online status, typing indicators, and message receipts. Perfect for learning real-time web development.

License

Notifications You must be signed in to change notification settings

subhashladumor1/laravel-socket.io

Repository files navigation

πŸ’¬ Laravel Socket.IO Real-time Chat Application

Laravel Socket.IO Bootstrap PHP MySQL

A stunning WhatsApp-like real-time chat application built with Laravel and Socket.IO

πŸš€ Quick Start β€’ πŸ“± Features β€’ πŸ›  Installation β€’ πŸ’» Usage β€’ πŸ”§ Troubleshooting

πŸ“Έ Screenshots

🏠 Dashboard Home Screen

Dashboard Home Screen

πŸ’¬ Chat Room Interface

Chat Room Interface


🌟 What is this?

This is a real-time chat application that brings the power of modern messaging to your Laravel application! Think WhatsApp, but built with cutting-edge web technologies. It features instant messaging, online status tracking, typing indicators, and message delivery receipts - all wrapped in a beautiful, responsive interface.

🎯 Perfect for:

  • Learning real-time web development
  • Building chat features for your apps
  • Understanding WebSocket communication
  • Creating modern messaging interfaces

✨ Features

πŸš€ Real-time Magic

  • ⚑ Instant messaging - Messages appear instantly
  • πŸ‘€ Typing indicators - See when someone is typing
  • 🟒 Online status - Know who's online/offline
  • βœ… Message receipts - Track delivery and read status
  • πŸ”„ Auto-reconnection - Never lose connection

πŸ’¬ WhatsApp-like Experience

  • 🎨 Beautiful UI - Clean, modern design
  • πŸ’­ Message bubbles - Sent/received message styling
  • πŸ“± Mobile responsive - Works on all devices
  • ⏰ Timestamps - See when messages were sent
  • πŸ”’ Unread counts - Badge notifications

πŸ” Security & Performance

  • πŸ›‘οΈ Laravel Sanctum - Secure API authentication
  • πŸ”’ Token-based auth - Modern authentication
  • πŸ—„οΈ MySQL database - Reliable data storage
  • ⚑ Optimized queries - Fast performance

πŸ›  Technology Stack

Backend Real-time Frontend Database
  • 🐘 Laravel 12.x
  • πŸ”§ PHP 8.2+
  • πŸ” Laravel Sanctum
  • ⚑ Socket.IO 4.8.1
  • 🟒 Node.js
  • 🌐 WebSockets
  • 🎨 Bootstrap 5
  • ⚑ JavaScript ES6+
  • πŸ“± jQuery 3.7.1
  • πŸ—„οΈ MySQL 5.7+
  • πŸ“Š Optimized indexes
  • πŸ”„ Real-time sync

πŸš€ Quick Start

⚑ Super Quick Setup (5 minutes!)

# 1️⃣ Clone and setup
git clone <your-repo-url>
cd laravel-socket.io

# 2️⃣ Install everything
composer install && npm install

# 3️⃣ Configure environment
cp .env.example .env
php artisan key:generate

# 4️⃣ Setup database (create MySQL database first)
php artisan migrate

# 5️⃣ Start both servers (2 terminals)
# Terminal 1:
php artisan serve --host=127.0.0.1 --port=8080

# Terminal 2:
node socket.js

# 6️⃣ Open browser
# Go to: http://127.0.0.1:8080

πŸŽ‰ That's it! You're ready to chat!


πŸ“‹ Prerequisites

Before we begin, make sure you have these installed:

βœ… Required Software

Software Version Download Link
🐘 PHP 8.2+ php.net
πŸ“¦ Composer Latest getcomposer.org
🟒 Node.js 16+ nodejs.org
πŸ—„οΈ MySQL 5.7+ mysql.com
πŸ”§ Git Latest git-scm.com

πŸ–₯️ System Requirements

  • RAM: 2GB minimum (4GB recommended)
  • Storage: 1GB free space
  • OS: Windows 10+, macOS 10.14+, or Linux

πŸ›  Installation

Step 1: πŸ“₯ Clone the Repository

# Clone the project
git clone <your-repository-url>
cd laravel-socket.io

# Or if you already have it locally
cd C:\Users\Subhash\Documents\GitHub\laravel-socket.io

Step 2: πŸ“¦ Install Dependencies

# Install PHP packages
composer install

# Install Node.js packages
npm install

What this installs:

  • 🐘 Laravel Framework & Sanctum
  • ⚑ Socket.IO & Express.js
  • 🎨 Bootstrap & jQuery
  • πŸ”§ Build tools (Vite)

Step 3: βš™οΈ Environment Configuration

# Copy environment file
cp .env.example .env

# Generate application key
php artisan key:generate

Edit your .env file:

APP_NAME="Laravel Socket Chat"
APP_ENV=local
APP_DEBUG=true
APP_URL=http://127.0.0.1:8080

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_socket_chat
DB_USERNAME=your_username
DB_PASSWORD=your_password

Step 4: πŸ—„οΈ Database Setup

Create MySQL Database:

CREATE DATABASE laravel_socket_chat;

Run Migrations:

php artisan migrate

This creates:

  • πŸ‘₯ users table (user accounts)
  • πŸ’¬ messages table (chat messages)
  • πŸ” personal_access_tokens table (API auth)
  • πŸ“Š sessions table (user sessions)

Step 5: πŸš€ Start the Servers

You need TWO terminals running:

πŸ–₯️ Terminal 1 - Laravel Server

php artisan serve --host=127.0.0.1 --port=8080

Expected output:

Starting Laravel development server: http://127.0.0.1:8080

⚑ Terminal 2 - Socket.IO Server

node socket.js

Expected output:

Socket.IO server running on port 3000

Step 6: 🌐 Access the Application

  1. Open your browser
  2. Go to: http://127.0.0.1:8080
  3. Register a new account or Login
  4. Click "Chat" to start messaging!

πŸ’» Usage Guide

🎯 Getting Started

1. First Time Setup

  • 🏠 Visit the home page
  • πŸ“ Click "Register" to create account
  • πŸ” Or "Login" if you have an account

2. Accessing Chat

  • πŸ’¬ Click "Chat" in navigation
  • πŸ‘₯ See list of all users
  • πŸ–±οΈ Click any user to start conversation

3. Sending Messages

  • ✍️ Type your message
  • ⏎ Press Enter or click Send
  • ⚑ Message appears instantly!

πŸ’¬ Chat Features

πŸ“± Message Status Indicators

Icon Status Meaning
⏰ Sending Message being sent to server
βœ… Delivered Message reached recipient's device
βœ…βœ… Read Message has been read by recipient

🟒 Online Status

  • Green dot = User is online
  • Gray dot = User is offline
  • Real-time updates = Status changes instantly

⌨️ Typing Indicators

  • See when someone is typing
  • Auto-hide after 1 second of inactivity
  • Real-time updates via Socket.IO

πŸ“± Mobile Experience

  • Responsive design works on all devices
  • Touch-friendly interface
  • Collapsible sidebar for mobile

πŸ”§ Advanced Features

πŸ“Š Message History

  • All messages stored in database
  • Previous conversations load automatically
  • Messages persist between sessions

πŸ”” Unread Notifications

  • Red badges show unread count
  • Counts reset when opening conversation
  • Real-time updates for new messages

πŸ‘€ Last Message Preview

  • See last message in each conversation
  • Timestamps show when sent
  • Updates in real-time

πŸ”Œ API Documentation

πŸ” Authentication

All API endpoints require authentication via Laravel Sanctum token.

Headers Required:

Authorization: Bearer {your_api_token}
Content-Type: application/json

πŸ“‘ API Endpoints

πŸ’¬ Send Message

POST /api/send

Request:

{
    "to": 2,
    "message": "Hello, how are you?"
}

Response:

{
    "success": true,
    "id": 123
}

πŸ“₯ Get Pending Messages

GET /api/pending

Response:

[
    {
        "id": 123,
        "from": 2,
        "from_name": "John Doe",
        "message": "Hello there!",
        "sent_at": "2024-01-15T10:30:00.000000Z"
    }
]

πŸ’­ Get Conversation

GET /api/messages?with=2

Response:

[
    {
        "id": 123,
        "from": 1,
        "from_name": "Jane Smith",
        "message": "Hello!",
        "sent_at": "2024-01-15T10:30:00.000000Z",
        "is_me": true
    }
]

βœ… Mark as Delivered

POST /api/mark-delivered/123

πŸ‘€ Mark as Read

POST /api/mark-read/123

πŸ“‹ Get Last Message

GET /api/last-message/2

⚑ Socket.IO Events

πŸ“€ Client to Server Events

// Join user room
socket.emit('join', userId);

// Typing indicator
socket.emit('typing', {
    user_id: userId,
    user_name: userName,
    to: recipientId
});

// Stop typing
socket.emit('stop-typing', {
    user_id: userId,
    to: recipientId
});

// Message read
socket.emit('message-read', {
    message_id: messageId,
    from: senderId,
    to: recipientId
});

πŸ“₯ Server to Client Events

// User came online
socket.on('online', (data) => {
    console.log('User online:', data.user_id);
});

// New message received
socket.on('new-message', (data) => {
    console.log('New message:', data);
});

// Someone is typing
socket.on('typing', (data) => {
    console.log('User typing:', data.user_name);
});

// Message was read
socket.on('message-read', (data) => {
    console.log('Message read:', data.message_id);
});

πŸ—„οΈ Database Schema

πŸ‘₯ Users Table

CREATE TABLE users (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    api_token VARCHAR(80) UNIQUE NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL
);

πŸ’¬ Messages Table

CREATE TABLE messages (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    from_id BIGINT NOT NULL,
    to_id BIGINT NOT NULL,
    message TEXT NOT NULL,
    delivered BOOLEAN DEFAULT 0,
    read_at TIMESTAMP NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    
    FOREIGN KEY (from_id) REFERENCES users(id),
    FOREIGN KEY (to_id) REFERENCES users(id)
);

πŸ”§ Troubleshooting

🚨 Common Issues & Solutions

1. Socket.IO Connection Failed

Problem: Browser shows connection errors Solutions:

  • βœ… Ensure Socket.IO server is running on port 3000
  • βœ… Check firewall settings
  • βœ… Verify CORS configuration
  • βœ… Check browser console for errors

2. Laravel Server Won't Start

Problem: php artisan serve fails Solutions:

  • βœ… Check if port 8080 is in use
  • βœ… Try different port: php artisan serve --port=8081
  • βœ… Verify PHP version: php --version
  • βœ… Check Laravel: php artisan --version

3. Database Connection Error

Problem: Migration fails Solutions:

  • βœ… Verify database credentials in .env
  • βœ… Ensure MySQL service is running
  • βœ… Check database exists
  • βœ… Verify user permissions

4. Messages Not Sending

Problem: Messages don't reach recipients Solutions:

  • βœ… Check Socket.IO server logs
  • βœ… Verify API token is valid
  • βœ… Check network connectivity
  • βœ… Review browser console

5. Authentication Issues

Problem: Can't login or API calls fail Solutions:

  • βœ… Clear browser cache and cookies
  • βœ… Check session configuration
  • βœ… Verify Sanctum setup
  • βœ… Regenerate API tokens

πŸ› Debug Mode

Enable detailed error information:

# In .env file
APP_DEBUG=true
LOG_LEVEL=debug

Check logs:

# Laravel logs
tail -f storage/logs/laravel.log

# Socket.IO logs (in terminal where node socket.js is running)

πŸš€ Deployment

🌐 Production Setup

1. Environment Configuration

APP_ENV=production
APP_DEBUG=false
APP_URL=https://yourdomain.com

# Use Redis for sessions in production
SESSION_DRIVER=redis
CACHE_DRIVER=redis

2. Server Requirements

  • 🐘 PHP 8.2+ with required extensions
  • πŸ—„οΈ MySQL 5.7+ or MariaDB 10.3+
  • 🟒 Node.js 16+ and NPM
  • 🌐 Web Server: Nginx or Apache
  • βš™οΈ Process Manager: PM2 or Supervisor

3. Deployment Steps

# Install production dependencies
composer install --optimize-autoloader --no-dev
npm install --production

# Generate optimized assets
npm run build
php artisan config:cache
php artisan route:cache
php artisan view:cache

# Run migrations
php artisan migrate --force

# Start services with PM2
pm2 start socket.js --name "socket-server"
pm2 start "php artisan serve --host=0.0.0.0 --port=8000" --name "laravel-server"

🎨 Customization

🎨 Styling

  • Modify Bootstrap classes in templates
  • Add custom CSS in resources/css
  • Update JavaScript for UI interactions
  • Test on different devices

⚑ Adding Features

  1. Create new API endpoints in MessageController
  2. Add new Socket.IO events in socket.js
  3. Update frontend JavaScript in chat.blade.php
  4. Add database migrations for new tables/columns

πŸ”§ Configuration

  • Socket.IO port: Modify socket.js
  • Laravel port: Change in php artisan serve
  • Database: Update .env file
  • CORS: Configure in socket.js

🀝 Contributing

πŸš€ How to Contribute

  1. 🍴 Fork the repository
  2. 🌿 Create feature branch: git checkout -b feature/amazing-feature
  3. πŸ’Ύ Commit changes: git commit -m 'Add amazing feature'
  4. πŸ“€ Push to branch: git push origin feature/amazing-feature
  5. πŸ”„ Open Pull Request

πŸ“‹ Code Standards

  • Follow PSR-12 coding standards
  • Write meaningful commit messages
  • Add tests for new features
  • Update documentation

πŸ“š Additional Resources

πŸ“– Documentation

πŸŽ“ Learning Resources

πŸ’¬ Community Support


πŸ“„ License

This project is open-sourced software licensed under the MIT license.


πŸ†˜ Support

Having issues? We're here to help!

  1. πŸ” Check the troubleshooting section above
  2. πŸ”Ž Search existing issues in the repository
  3. πŸ†• Create a new issue with detailed information
  4. πŸ’¬ Join the community for help and discussions

πŸŽ‰ Conclusion

Congratulations! You now have a complete real-time chat application! 🎊

What you've built:

  • βœ… Real-time messaging with Socket.IO
  • βœ… Beautiful WhatsApp-like interface
  • βœ… Message status tracking
  • βœ… Online/offline status
  • βœ… Typing indicators
  • βœ… Mobile-responsive design
  • βœ… Secure authentication

Next steps:

  • πŸš€ Deploy to production
  • 🎨 Customize the design
  • ⚑ Add new features
  • πŸ“± Test on different devices

Happy coding! πŸš€πŸ’»


Made with ❀️ using Laravel & Socket.IO

⭐ Star this repo β€’ πŸ› Report Bug β€’ πŸ’‘ Request Feature

About

πŸ’¬ Real-time chat application built with Laravel & Socket.IO. Features WhatsApp-like UI, instant messaging, online status, typing indicators, and message receipts. Perfect for learning real-time web development.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project

  •  

Packages

No packages published