Troubleshooting - luckydeva03/barbershop_app GitHub Wiki

🔧 Troubleshooting

Panduan komprehensif untuk debugging dan menyelesaikan masalah umum pada barbershop management system.

🎯 Common Issues Overview

Masalah yang sering terjadi:

  • Installation Issues: Dependency conflicts, permission problems
  • Database Issues: Connection errors, migration failures, query problems
  • Authentication Issues: Login failures, session problems, OAuth errors
  • Performance Issues: Slow queries, memory issues, timeout errors
  • File Upload Issues: Storage problems, permission errors
  • API Integration Issues: Google OAuth, WhatsApp API, Maps API

🚀 Installation & Setup Issues

1. Composer Dependencies

Issue: Composer Install Fails

# Error: Package conflicts or missing requirements
composer install
# or
composer update

Solutions:

# Clear composer cache
composer clear-cache

# Install with specific PHP version
php8.2 /usr/local/bin/composer install

# Install ignoring platform requirements (use carefully)
composer install --ignore-platform-reqs

# Update to latest compatible versions
composer update --with-all-dependencies

# Check PHP extensions
php -m | grep -E "(pdo|mbstring|openssl|tokenizer|xml|ctype|json|curl)"

Issue: NPM/Node Dependencies

# Error: Node version conflicts
npm install

Solutions:

# Clear npm cache
npm cache clean --force

# Remove node_modules and reinstall
rm -rf node_modules package-lock.json
npm install

# Use specific node version
nvm use 18
npm install

# Use yarn instead of npm
yarn install

2. Environment Configuration

Issue: .env File Problems

# Error: Environment variables not loaded

Solutions:

# Copy example environment file
cp .env.example .env

# Generate application key
php artisan key:generate

# Clear configuration cache
php artisan config:clear
php artisan config:cache

# Check environment loading
php artisan tinker
>>> config('app.name')
>>> env('DB_CONNECTION')

Issue: File Permissions

# Error: Permission denied on storage/logs

Solutions:

# Linux/macOS permissions
sudo chown -R www-data:www-data storage bootstrap/cache
chmod -R 775 storage bootstrap/cache

# Alternative ownership
sudo chown -R $USER:www-data storage bootstrap/cache
chmod -R 775 storage bootstrap/cache

# SELinux (if enabled)
setsebool -P httpd_can_network_connect 1
setsebool -P httpd_unified 1

3. Database Setup Issues

Issue: Database Connection Failed

SQLSTATE[HY000] [2002] Connection refused

Diagnostic Steps:

# Check MySQL service
sudo systemctl status mysql
# or
brew services list | grep mysql

# Test connection manually
mysql -h 127.0.0.1 -u root -p

# Check port availability
netstat -tlnp | grep :3306

Solutions:

# Start MySQL service
sudo systemctl start mysql
# or
brew services start mysql

# Reset MySQL password
sudo mysql -u root
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'newpassword';
FLUSH PRIVILEGES;

# Create database and user
CREATE DATABASE barbershop_db;
CREATE USER 'barbershop_user'@'localhost' IDENTIFIED BY 'secure_password';
GRANT ALL PRIVILEGES ON barbershop_db.* TO 'barbershop_user'@'localhost';
FLUSH PRIVILEGES;

💾 Database Issues

1. Migration Problems

Issue: Migration Fails

php artisan migrate
# Error: Table already exists or constraint violation

Solutions:

# Check migration status
php artisan migrate:status

# Reset all migrations (WARNING: destroys data)
php artisan migrate:reset
php artisan migrate

# Rollback specific number of migrations
php artisan migrate:rollback --step=3

# Fresh migrate with seeding
php artisan migrate:fresh --seed

# Force migrate in production
php artisan migrate --force

# Skip specific migration
php artisan migrate:rollback --path=database/migrations/specific_migration.php

Issue: Foreign Key Constraint Errors

SQLSTATE[23000]: Integrity constraint violation

Solutions:

// In migration file, disable foreign key checks temporarily
public function up()
{
    Schema::disableForeignKeyConstraints();
    
    Schema::create('table_name', function (Blueprint $table) {
        // Table definition
    });
    
    Schema::enableForeignKeyConstraints();
}

// Or in database seeder
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
// Seeding operations
DB::statement('SET FOREIGN_KEY_CHECKS=1;');

2. Query Performance Issues

Issue: Slow Database Queries

# Enable query logging
DB::enableQueryLog();
// Your operations
dd(DB::getQueryLog());

Diagnostic Tools:

// In AppServiceProvider boot method
if (app()->environment('local')) {
    DB::listen(function ($query) {
        if ($query->time > 1000) { // Queries longer than 1 second
            Log::warning('Slow query detected', [
                'sql' => $query->sql,
                'bindings' => $query->bindings,
                'time' => $query->time
            ]);
        }
    });
}

Solutions:

-- Add indexes for slow queries
ALTER TABLE users ADD INDEX idx_email_active (email, is_active);
ALTER TABLE reviews ADD INDEX idx_store_created (store_id, created_at);
ALTER TABLE history_points ADD INDEX idx_user_type_created (user_id, type, created_at);

-- Analyze query performance
EXPLAIN SELECT * FROM users WHERE email = '[email protected]';

-- Check table statistics
SHOW TABLE STATUS LIKE 'users';

3. Connection Pool Issues

Issue: Too Many Connections

SQLSTATE[08004] [1040] Too many connections

Solutions:

-- Check current connections
SHOW PROCESSLIST;
SHOW STATUS LIKE 'Threads_connected';

-- Check max connections
SHOW VARIABLES LIKE 'max_connections';

-- Increase max connections (temporarily)
SET GLOBAL max_connections = 200;

-- Make permanent in my.cnf
[mysqld]
max_connections = 200
// In config/database.php - Optimize connection pooling
'mysql' => [
    // ... other config
    'options' => [
        PDO::ATTR_PERSISTENT => false, // Disable persistent connections
        PDO::ATTR_TIMEOUT => 30,
        PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
    ],
],

🔐 Authentication Issues

1. Login Problems

Issue: Session Not Working

// User logs in but session doesn't persist

Diagnostic Steps:

// Check session configuration
php artisan tinker
>>> config('session')

// Test session manually
session(['test' => 'value']);
echo session('test');

// Check session files
ls -la storage/framework/sessions/

Solutions:

# Clear sessions
php artisan session:clear
rm -rf storage/framework/sessions/*

# Check session driver
# In .env
SESSION_DRIVER=file
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null

# For Redis sessions
SESSION_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

Issue: CSRF Token Mismatch

419 | Page Expired

Solutions:

// Check CSRF token in blade templates
<meta name="csrf-token" content="{{ csrf_token() }}">

// In JavaScript
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

// Exclude routes from CSRF (use carefully)
// In app/Http/Middleware/VerifyCsrfToken.php
protected $except = [
    'webhook/*',
    'api/*',
];

2. Google OAuth Issues

Issue: OAuth Redirect Mismatch

Error: redirect_uri_mismatch

Solutions:

# Check Google Console settings
# Authorized redirect URIs should include:
https://yourdomain.com/auth/google/callback
http://localhost:8000/auth/google/callback (for local development)

# Check .env configuration
GOOGLE_CLIENT_ID=your_client_id
GOOGLE_CLIENT_SECRET=your_client_secret
GOOGLE_REDIRECT_URL=https://yourdomain.com/auth/google/callback

Issue: OAuth Token Expired

// Error: The access token provided is invalid

Solutions:

// Implement token refresh in User model
public function refreshGoogleToken()
{
    $client = new Google_Client();
    $client->setClientId(config('services.google.client_id'));
    $client->setClientSecret(config('services.google.client_secret'));
    $client->refreshToken($this->google_refresh_token);
    
    $newToken = $client->getAccessToken();
    
    $this->update([
        'google_access_token' => $newToken['access_token'],
        'google_expires_at' => now()->addSeconds($newToken['expires_in']),
    ]);
}

// Check token validity before API calls
if ($user->google_expires_at < now()) {
    $user->refreshGoogleToken();
}

⚡ Performance Issues

1. Memory Issues

Issue: Memory Limit Exceeded

PHP Fatal error: Allowed memory size exhausted

Solutions:

// Increase memory limit temporarily
ini_set('memory_limit', '512M');

// In .env
MEMORY_LIMIT=512M

// Optimize queries for large datasets
// Instead of:
$users = User::all();

// Use:
User::chunk(1000, function ($users) {
    foreach ($users as $user) {
        // Process user
    }
});

// Or use cursor for memory efficiency
foreach (User::cursor() as $user) {
    // Process user
}

Issue: High Memory Usage

# Monitor memory usage
php artisan tinker
>>> memory_get_usage(true) / 1024 / 1024 . ' MB'
>>> memory_get_peak_usage(true) / 1024 / 1024 . ' MB'

Solutions:

// Optimize eager loading
// Instead of N+1 queries:
$stores = Store::all();
foreach ($stores as $store) {
    echo $store->reviews->count(); // N+1 problem
}

// Use eager loading:
$stores = Store::with('reviews')->get();
foreach ($stores as $store) {
    echo $store->reviews->count();
}

// Use lazy eager loading for dynamic relationships
$stores = Store::all();
$stores->load('reviews.user');

2. Timeout Issues

Issue: Max Execution Time Exceeded

PHP Fatal error: Maximum execution time exceeded

Solutions:

// Increase execution time for specific operations
set_time_limit(300); // 5 minutes

// In .env
MAX_EXECUTION_TIME=300

// Use queue for long-running tasks
// Create job
php artisan make:job ProcessLargeDataset

// In job class
class ProcessLargeDataset implements ShouldQueue
{
    public $timeout = 300;
    
    public function handle()
    {
        // Long-running operation
    }
}

// Dispatch job
ProcessLargeDataset::dispatch($data);

3. Cache Issues

Issue: Cache Not Working

// Cache not storing or retrieving data

Solutions:

# Clear all caches
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear

# Check cache driver
php artisan tinker
>>> config('cache.default')
>>> Cache::put('test', 'value', 60)
>>> Cache::get('test')

# Test Redis connection (if using Redis)
redis-cli ping

Issue: Cache Permission Problems

# Error: Permission denied writing cache files

Solutions:

# Fix cache directory permissions
sudo chown -R www-data:www-data storage/framework/cache
chmod -R 775 storage/framework/cache

# Clear cache directory
rm -rf storage/framework/cache/*

📁 File Upload Issues

1. Upload Failures

Issue: File Upload Size Limit

The file exceeds the maximum allowed size

Solutions:

// Check PHP limits
php -r "echo 'upload_max_filesize: ' . ini_get('upload_max_filesize') . PHP_EOL;"
php -r "echo 'post_max_size: ' . ini_get('post_max_size') . PHP_EOL;"
php -r "echo 'max_file_uploads: ' . ini_get('max_file_uploads') . PHP_EOL;"

// In php.ini
upload_max_filesize = 10M
post_max_size = 10M
max_file_uploads = 20

// In Laravel validation
'image' => 'required|image|max:10240' // 10MB in KB

Issue: Storage Disk Not Found

Disk [s3] does not have a configured driver

Solutions:

# Install required packages
composer require league/flysystem-aws-s3-v3

# Check filesystem configuration
php artisan tinker
>>> config('filesystems.disks')

# Test storage disk
>>> Storage::disk('public')->put('test.txt', 'test content')
>>> Storage::disk('public')->exists('test.txt')

2. Image Processing Issues

Issue: GD Extension Not Found

Class 'Imagick' not found or GD extension missing

Solutions:

# Install GD extension
sudo apt-get install php-gd
# or
brew install [email protected] --with-gd

# Install ImageMagick
sudo apt-get install php-imagick
# or
brew install imagemagick

# Check extensions
php -m | grep -E "(gd|imagick)"

🌐 API Integration Issues

1. Google Maps API

Issue: API Key Invalid

{
  "error_message": "The provided API key is invalid",
  "status": "REQUEST_DENIED"
}

Solutions:

# Check API key in Google Console
# Enable required APIs:
# - Maps JavaScript API
# - Geocoding API
# - Places API

# Set API restrictions properly
# In .env
GOOGLE_MAPS_API_KEY=your_valid_api_key

# Test API key
curl "https://maps.googleapis.com/maps/api/geocode/json?address=Jakarta&key=YOUR_API_KEY"

2. WhatsApp API Issues

Issue: Webhook Verification Failed

403 Forbidden - Webhook verification failed

Solutions:

// In WhatsApp webhook controller
public function verify(Request $request)
{
    $mode = $request->get('hub_mode');
    $token = $request->get('hub_verify_token');
    $challenge = $request->get('hub_challenge');
    
    if ($mode === 'subscribe' && $token === config('services.whatsapp.verify_token')) {
        return response($challenge, 200);
    }
    
    return response('Forbidden', 403);
}

// Check webhook URL and verify token
# In .env
WHATSAPP_VERIFY_TOKEN=your_verify_token_here

🔍 Debugging Tools & Techniques

1. Laravel Debugging

Debug Mode Configuration

// In .env
APP_DEBUG=true
LOG_LEVEL=debug

// Enable query logging
// In AppServiceProvider
public function boot()
{
    if (config('app.debug')) {
        DB::listen(function ($query) {
            Log::info('Query executed', [
                'sql' => $query->sql,
                'bindings' => $query->bindings,
                'time' => $query->time . 'ms'
            ]);
        });
    }
}

Useful Debugging Commands

# Debug application state
php artisan about

# Check route list
php artisan route:list

# Check configuration
php artisan config:show

# Tinker for interactive debugging
php artisan tinker
>>> User::count()
>>> config('database.default')
>>> cache()->get('key')

# Queue monitoring
php artisan queue:monitor redis:default --max-time=30

# Check failed jobs
php artisan queue:failed
php artisan queue:retry all

2. Log Analysis

Useful Log Commands

# Real-time log monitoring
tail -f storage/logs/laravel.log

# Search for specific errors
grep -r "SQLSTATE" storage/logs/
grep -r "Exception" storage/logs/ | head -20

# Log rotation check
ls -la storage/logs/

# Clear old logs
find storage/logs -name "*.log" -mtime +30 -delete

Custom Debug Helper

// Create app/Helpers/DebugHelper.php
class DebugHelper
{
    public static function logQuery($query, $bindings = [])
    {
        Log::debug('Manual Query Debug', [
            'sql' => $query,
            'bindings' => $bindings,
            'execution_time' => microtime(true)
        ]);
    }
    
    public static function dumpMemory($label = 'Memory Check')
    {
        Log::debug($label, [
            'memory_usage' => memory_get_usage(true) / 1024 / 1024 . ' MB',
            'memory_peak' => memory_get_peak_usage(true) / 1024 / 1024 . ' MB'
        ]);
    }
    
    public static function logRequest($request)
    {
        Log::debug('Request Debug', [
            'url' => $request->fullUrl(),
            'method' => $request->method(),
            'headers' => $request->headers->all(),
            'data' => $request->except(['password', 'password_confirmation'])
        ]);
    }
}

🚨 Emergency Procedures

1. Application Down

Quick Recovery Steps

# 1. Check application status
curl -I https://yourdomain.com

# 2. Check server resources
top
df -h
free -m

# 3. Check web server
sudo systemctl status apache2
# or
sudo systemctl status nginx

# 4. Check database
sudo systemctl status mysql
mysql -u root -p -e "SELECT 1"

# 5. Check logs immediately
tail -50 storage/logs/laravel.log
tail -50 /var/log/apache2/error.log

# 6. Quick fixes
php artisan down --message="Maintenance in progress"
php artisan cache:clear
php artisan config:clear
php artisan up

2. Database Emergency

Database Recovery

# 1. Check database status
mysqladmin status -u root -p

# 2. Check table status
mysql -u root -p -e "CHECK TABLE users, stores, reviews;"

# 3. Repair corrupted tables
mysql -u root -p -e "REPAIR TABLE users;"

# 4. Restore from backup
mysql -u root -p barbershop_db < backup_file.sql

# 5. Reset permissions if needed
mysql -u root -p -e "FLUSH PRIVILEGES;"

3. Performance Emergency

Immediate Performance Fixes

# 1. Clear all caches
php artisan optimize:clear

# 2. Restart web server
sudo systemctl restart apache2

# 3. Restart database
sudo systemctl restart mysql

# 4. Check for resource intensive processes
ps aux --sort=-%cpu | head -10
ps aux --sort=-%mem | head -10

# 5. Kill problematic processes (if safe)
kill -9 [PID]

# 6. Increase resource limits temporarily
ulimit -n 65536  # Increase file descriptor limit

📞 Support & Resources

1. Getting Help

Log Collection for Support

# Collect system information
php artisan about > system_info.txt

# Collect recent logs
tail -1000 storage/logs/laravel.log > recent_logs.txt

# Collect configuration (sanitized)
php artisan config:show --except=password,secret,key > config_info.txt

# Check disk space and permissions
ls -la storage/ > permissions.txt
df -h > disk_space.txt

2. Monitoring Setup

Basic Monitoring Script

#!/bin/bash
# health_check.sh

echo "=== Health Check $(date) ==="

# Check web server response
if curl -f -s http://localhost/health > /dev/null; then
    echo "✅ Web server responding"
else
    echo "❌ Web server not responding"
fi

# Check database
if php artisan tinker --execute="DB::connection()->getPdo(); echo 'Database OK';" 2>/dev/null; then
    echo "✅ Database accessible"
else
    echo "❌ Database connection failed"
fi

# Check disk space
DISK_USAGE=$(df / | awk 'NR==2{print $5}' | sed 's/%//')
if [ $DISK_USAGE -gt 80 ]; then
    echo "⚠️ Disk usage high: ${DISK_USAGE}%"
else
    echo "✅ Disk usage normal: ${DISK_USAGE}%"
fi

echo "=========================="

3. Maintenance Checklist

Daily Maintenance

# Daily maintenance script
#!/bin/bash

# Clear old logs
find storage/logs -name "*.log" -mtime +7 -delete

# Clear expired sessions
php artisan session:gc

# Optimize application
php artisan optimize

# Update statistics
php artisan queue:work --once

# Check for failed jobs
php artisan queue:failed

Weekly Maintenance

# Weekly maintenance script
#!/bin/bash

# Backup database
php artisan backup:database --type=full

# Clear old cache files
php artisan cache:clear

# Update composer dependencies (if needed)
composer update --no-dev

# Restart services
sudo systemctl restart apache2
sudo systemctl restart mysql