This guide will help you set up and configure the Laravel backend for your React-WordPress application.
Before setting up the Laravel backend, ensure you have the following installed:
- PHP 8.1 or higher
- Composer (PHP dependency manager)
- MySQL 8.0 or higher (or MariaDB 10.3+)
- Redis (optional, for caching)
- Node.js 16+ (for the React frontend)
# Navigate to Laravel backend directory
cd laravel-backend
# Install PHP dependencies
composer install
# Return to root directory
cd ..# Copy environment file
cd laravel-backend
cp .env.example .env
# Generate application key
php artisan key:generateEdit the .env file in the laravel-backend directory:
# Database Configuration
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_wordpress
DB_USERNAME=your_username
DB_PASSWORD=your_password
# WordPress API Configuration
WORDPRESS_API_URL=https://public-api.wordpress.com/rest/v1.1/sites/jcreforme.home.blog
WORDPRESS_SITE_URL=https://jcreforme.home.blog
# Cache Configuration (Redis recommended)
CACHE_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
# CORS Configuration for React
CORS_ALLOWED_ORIGINS=http://localhost:3000,http://localhost:3001# Create database (MySQL command line)
mysql -u root -p -e "CREATE DATABASE laravel_wordpress;"
# Run migrations
php artisan migrate# Start Laravel development server
php artisan serve --port=8000The Laravel API will be available at: http://localhost:8000
For a complete containerized setup:
# Start all services (React + Laravel + WordPress + MySQL + Redis)
npm run docker:prod
# Or run in background
npm run docker:prod:bgThis will start:
- React frontend:
http://localhost:3000 - Laravel API:
http://localhost:8001 - WordPress:
http://localhost:8080 - phpMyAdmin:
http://localhost:8081
The Laravel backend can be configured to work with different WordPress sources:
WORDPRESS_API_URL=https://public-api.wordpress.com/rest/v1.1/sites/jcreforme.home.blog
WORDPRESS_SITE_URL=https://jcreforme.home.blogWORDPRESS_API_URL=https://your-wordpress-site.com/wp-json/wp/v2
WORDPRESS_SITE_URL=https://your-wordpress-site.com
WORDPRESS_JWT_TOKEN=your-jwt-token-hereWORDPRESS_API_URL=http://localhost:8080/wp-json/wp/v2
WORDPRESS_SITE_URL=http://localhost:8080CACHE_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
WORDPRESS_CACHE_TTL=300CACHE_DRIVER=file
WORDPRESS_CACHE_TTL=300# Rate limiting (requests per minute)
WORDPRESS_RATE_LIMIT=60
# CORS origins (comma-separated)
CORS_ALLOWED_ORIGINS=http://localhost:3000,https://your-domain.com
# API security
WORDPRESS_JWT_SECRET=your-secure-secret-keyThe main package.json includes helpful scripts for Laravel management:
# Laravel-specific commands
npm run laravel:install # Install PHP dependencies
npm run laravel:setup # Setup environment and generate key
npm run laravel:migrate # Run database migrations
npm run laravel:serve # Start Laravel server
npm run laravel:cache # Cache configuration and routes
npm run laravel:test # Run Laravel tests
# Full-stack development
npm run dev:full # Start both React and Laravel servers
npm run setup:all # Setup both Node.js and PHP dependenciesOnce the Laravel backend is running, you can access these endpoints:
GET /api/health # API health check
GET /api/config # API configuration
GET /api/wordpress/posts # Get WordPress posts
GET /api/wordpress/posts/{id} # Get specific post
GET /api/wordpress/search?q={term} # Search posts
GET /api/wordpress/categories # Get categories
GET /api/wordpress/tags # Get tags
GET /api/wordpress/stats # Get blog statistics
POST /api/wordpress/posts # Create new post
PUT /api/wordpress/posts/{id} # Update post
DELETE /api/wordpress/posts/{id} # Delete post
POST /api/wordpress/sync # Sync content
DELETE /api/wordpress/cache # Clear cache
curl http://localhost:8000/api/healthExpected response:
{
"status": "ok",
"timestamp": "2025-07-15T12:00:00.000000Z",
"version": "1.0.0",
"environment": "local"
}curl http://localhost:8000/api/wordpress/posts?per_page=5curl http://localhost:8000/api/wordpress/statsError: composer: command not found
Solution: Install Composer globally
# Download and install Composer
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php
php -r "unlink('composer-setup.php');"
sudo mv composer.phar /usr/local/bin/composerError: SQLSTATE[HY000] [2002] Connection refused
Solutions:
- Ensure MySQL is running
- Check database credentials in
.env - Create the database if it doesn't exist
- Verify MySQL port (default: 3306)
Error: Connection refused [tcp://127.0.0.1:6379]
Solutions:
- Install and start Redis:
# Ubuntu/Debian sudo apt install redis-server sudo systemctl start redis # macOS (with Homebrew) brew install redis brew services start redis # Windows (with Docker) docker run -d -p 6379:6379 redis:alpine
- Or use file-based caching:
CACHE_DRIVER=file
Error: Access to fetch at 'http://localhost:8000/api/...' from origin 'http://localhost:3000' has been blocked by CORS policy
Solution: Update CORS settings in Laravel .env:
CORS_ALLOWED_ORIGINS=http://localhost:3000,http://localhost:3001Error: Laravel returns 500 error when fetching WordPress data
Solutions:
- Check WordPress API URL is correct
- Verify network connectivity
- Check Laravel logs:
laravel-backend/storage/logs/laravel.log - Test WordPress API directly in browser
Error: The stream or file could not be opened in append mode
Solution: Set proper file permissions
cd laravel-backend
sudo chown -R www-data:www-data storage bootstrap/cache
sudo chmod -R 775 storage bootstrap/cacheEnable debug mode for detailed error information:
APP_DEBUG=true
LOG_LEVEL=debugFor production, update these settings in .env:
APP_ENV=production
APP_DEBUG=false
APP_URL=https://your-domain.com
# Use strong, unique keys
APP_KEY=base64:your-generated-key
# Production database
DB_HOST=your-production-db-host
DB_DATABASE=your-production-db
DB_USERNAME=your-production-user
DB_PASSWORD=your-secure-password
# Production cache
CACHE_DRIVER=redis
REDIS_HOST=your-redis-host
# Production CORS
CORS_ALLOWED_ORIGINS=https://your-frontend-domain.com# Cache configuration and routes
php artisan config:cache
php artisan route:cache
php artisan view:cache
# Optimize Composer autoloader
composer install --no-dev --optimize-autoloaderFor production, use a proper web server like Nginx:
server {
listen 80;
server_name your-api-domain.com;
root /var/www/laravel-backend/public;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
index index.php;
charset utf-8;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
error_page 404 /index.php;
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.(?!well-known).* {
deny all;
}
}Add to your PHP configuration:
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=2Optimize Redis configuration:
maxmemory 256mb
maxmemory-policy allkeys-lru
save 900 1
Add indexes for better performance:
-- Add to your migration
Schema::table('posts', function (Blueprint $table) {
$table->index(['post_status', 'post_type']);
$table->index('post_date');
});- Never commit
.envfiles to version control - Use strong, unique passwords and keys
- Regularly rotate API keys and secrets
- Configure appropriate rate limits for your use case
- Monitor API usage and adjust limits as needed
- All input is validated using Laravel's validation rules
- HTML content is sanitized to prevent XSS attacks
- Always use HTTPS in production
- Configure SSL certificates properly
- Update CORS settings for HTTPS origins
- Laravel logs:
laravel-backend/storage/logs/laravel.log - Nginx logs:
/var/log/nginx/error.log - PHP logs:
/var/log/php/error.log
This setup guide should get your Laravel backend up and running successfully. If you encounter any issues not covered here, check the logs and refer to the official documentation for the specific components involved.