# Troubleshooting Guide

This guide addresses common issues encountered during development and deployment.

## Installation Issues

### Composer Install Fails

**Error**: Memory limit exhausted

```bash
# Solution: Increase memory limit
COMPOSER_MEMORY_LIMIT=-1 composer install
```

**Error**: Missing PHP extension

```bash
# Check missing extensions
php -m

# Install missing extension (Ubuntu example)
sudo apt-get install php8.2-imagick php8.2-redis
```

### npm Install Fails

**Error**: Node version mismatch

```bash
# Check Node version
node -v

# Use nvm to switch versions
nvm install 18
nvm use 18
```

### Database Connection Failed

**Error**: `SQLSTATE[HY000] [2002] Connection refused`

1. Verify MySQL is running:
   ```bash
   sudo service mysql status
   ```

2. Check credentials in `.env`:
   ```bash
   php artisan tinker
   >>> DB::connection()->getPdo();
   ```

3. Verify host and port:
   ```bash
   mysql -h 127.0.0.1 -P 3306 -u username -p
   ```

## Runtime Errors

### Class Not Found

```bash
# Regenerate autoload files
composer dump-autoload

# Clear all caches
php artisan optimize:clear
```

### Configuration Not Loading

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

# Verify .env file exists and is readable
cat .env | head -5
```

### Storage Permission Denied

```bash
# Fix storage permissions
chmod -R 775 storage bootstrap/cache
chown -R www-data:www-data storage bootstrap/cache
```

### Session/Cache Issues

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

# Or use optimize:clear
php artisan optimize:clear
```

## API Issues

### 401 Unauthorized

1. Check token is included in header:
   ```
   Authorization: Bearer your_token_here
   ```

2. Verify token hasn't expired
3. Check Sanctum configuration

### 403 Forbidden

1. User lacks required permission
2. Check role assignments:
   ```bash
   php artisan tinker
   >>> User::find(1)->permissions;
   >>> User::find(1)->roles;
   ```

### 419 CSRF Token Mismatch

For API requests, ensure you're using Sanctum token authentication, not session-based.

### 422 Validation Failed

Check request body matches validation rules. Response will include specific field errors.

### 500 Internal Server Error

1. Check Laravel logs:
   ```bash
   tail -f storage/logs/laravel.log
   ```

2. Enable debug mode temporarily:
   ```env
   APP_DEBUG=true
   ```

## Queue Issues

### Jobs Not Processing

1. Check queue worker is running:
   ```bash
   php artisan queue:work
   ```

2. Check failed jobs:
   ```bash
   php artisan queue:failed
   ```

3. Retry failed jobs:
   ```bash
   php artisan queue:retry all
   ```

### Horizon Not Starting

```bash
# Check Redis connection
php artisan tinker
>>> Redis::ping();

# Restart Horizon
php artisan horizon:terminate
php artisan horizon
```

## Performance Issues

### Slow API Responses

1. Check database queries with Telescope
2. Enable query logging:
   ```php
   DB::enableQueryLog();
   // ... your code
   dd(DB::getQueryLog());
   ```

3. Check for N+1 queries:
   ```bash
   # Install Laravel Debugbar
   composer require barryvdh/laravel-debugbar --dev
   ```

### High Memory Usage

1. Check for memory leaks in queued jobs
2. Use chunking for large datasets:
   ```php
   Model::chunk(1000, function ($records) {
       // Process records
   });
   ```

## Testing Issues

### Tests Failing

```bash
# Use testing environment
php artisan test --env=testing

# Refresh test database
php artisan migrate:fresh --env=testing
```

### Database State Issues

```bash
# Use RefreshDatabase trait in tests
use Illuminate\Foundation\Testing\RefreshDatabase;

class ExampleTest extends TestCase
{
    use RefreshDatabase;
}
```

## Deployment Issues

### Deployment Checklist

```bash
# 1. Install dependencies
composer install --no-dev --optimize-autoloader

# 2. Run migrations
php artisan migrate --force

# 3. Cache configuration
php artisan config:cache
php artisan route:cache
php artisan view:cache

# 4. Restart queue workers
php artisan queue:restart
```

### Symlink Issues

```bash
# Recreate storage link
rm -rf public/storage
php artisan storage:link
```

## Getting Help

If you're still experiencing issues:

1. Check existing documentation
2. Search the issue tracker
3. Review recent commits for breaking changes
4. Contact the development team with:
   - Error message
   - Steps to reproduce
   - Environment details
   - Relevant log entries
