Building Scalable Microservices with Laravel 13 Octane
Microservices architecture is a popular approach for building scalable and maintainable applications. Laravel 13 Octane is a high-performance framework designed to optimize Laravel applications by leveraging long-lived workers and task scheduling, making it an excellent choice for microservices. This tutorial guides you through setting up a microservices architecture using Laravel 13 Octane, focusing on creating responsive and efficient services.
Prerequisites
Before you start, ensure you have the following installed on your system:
- PHP 8.1 or higher
- Composer
- Node.js and npm
- Redis (for task scheduling and caching)
- A web server like Nginx or Apache
You can install these prerequisites using the following commands:
# Install PHP 8.1
sudo apt update
sudo apt install php8.1 php8.1-cli php8.1-fpm php8.1-mbstring php8.1-xml php8.1-bcmath php8.1-json php8.1-zip php8.1-curl
# Install Composer
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
# Install Node.js and npm
curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -
sudo apt install -y nodejs
# Install Redis
sudo apt install redis-server
# Start Redis service
sudo systemctl start redis
sudo systemctl enable redis
Project Structure
We will create a simple microservices project with the following structure:
laravel-microservices/
├── api-gateway/
├── user-service/
└── product-service/
Each service will be a separate Laravel application.
Step 1: Setting Up the API Gateway
The API Gateway is the entry point for handling client requests and routing them to the appropriate microservices.
1.1 Create a New Laravel Project
Create a new Laravel project for the API Gateway:
composer create-project laravel/laravel api-gateway
1.2 Install Laravel Octane
Navigate to the api-gateway directory and install Laravel Octane:
cd api-gateway
composer require laravel/octane
1.3 Configure Octane
Run the Octane installation command:
php artisan octane:install
This command will prompt you to choose a server. Select "Swoole" for better performance.
1.4 Run the API Gateway
Start the Octane server:
php artisan octane:start --watch
This command will start the API Gateway, watching for changes in your code.
Step 2: Creating the User Service
The User Service will manage user-related operations, such as registration and authentication.
2.1 Create a New Laravel Project
Create a new Laravel project for the User Service:
composer create-project laravel/laravel user-service
2.2 Install Laravel Octane
Navigate to the user-service directory and install Laravel Octane:
cd user-service
composer require laravel/octane
2.3 Configure Octane
Run the Octane installation command:
php artisan octane:install
Choose "Swoole" as the server option.
2.4 Set Up Authentication
Install Laravel Breeze for simple authentication scaffolding:
composer require laravel/breeze --dev
php artisan breeze:install
npm install && npm run dev
php artisan migrate
2.5 Run the User Service
Start the Octane server for the User Service:
php artisan octane:start --watch
Step 3: Creating the Product Service
The Product Service will handle operations related to product management.
3.1 Create a New Laravel Project
Create a new Laravel project for the Product Service:
composer create-project laravel/laravel product-service
3.2 Install Laravel Octane
Navigate to the product-service directory and install Laravel Octane:
cd product-service
composer require laravel/octane
3.3 Configure Octane
Run the Octane installation command:
php artisan octane:install
Select "Swoole" as the server option.
3.4 Set Up Product Model and Migration
Create a Product model and migration:
php artisan make:model Product -m
Edit the migration file database/migrations/xxxx_xx_xx_xxxxxx_create_products_table.php to define the product schema:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up() {
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description');
$table->decimal('price', 8, 2);
$table->timestamps();
});
}
public function down() {
Schema::dropIfExists('products');
}
};
Run the migration to create the products table:
php artisan migrate
3.5 Run the Product Service
Start the Octane server for the Product Service:
php artisan octane:start --watch
In these steps, we have set up three separate Laravel applications using Octane. Each service is configured to run independently, allowing for scalable microservices architecture. In the next part of this tutorial, we will integrate these services and implement communication between them.
Step 4: Integrating the Microservices
Now that we have individual services set up, let's integrate them using the API Gateway. We'll configure the API Gateway to route requests to the appropriate service.
4.1 Configure API Gateway Routes
Navigate to the api-gateway project and edit the routes/api.php file to define the routes for user and product services:
<?php
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Route;
Route::prefix('api')->group(function () {
Route::get('/users', function () {
return Http::get('http://localhost:8001/api/users');
});
Route::get('/products', function () {
return Http::get('http://localhost:8002/api/products');
});
});
4.2 Enable CORS
Ensure that CORS is enabled in both the User and Product services by adding the following to the app/Http/Middleware/Kernel.php file under $middlewareGroups:
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\Cors::class, // Add this line
],
Then, create the CORS middleware if it doesn't exist:
php artisan make:middleware Cors
Edit the app/Http/Middleware/Cors.php file:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class Cors
{
public function handle(Request $request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'Content-Type, X-Auth-Token, Authorization, Origin');
}
}
4.3 Test the Integration
Start the Octane servers for all services:
# In api-gateway
php artisan octane:start --watch --port=8000
# In user-service
php artisan octane:start --watch --port=8001
# In product-service
php artisan octane:start --watch --port=8002
Test the API Gateway by accessing http://localhost:8000/api/users and http://localhost:8000/api/products in your browser or via a tool like Postman.
Complete Working Example
Here's a summary of the complete setup:
API Gateway
- Routes: Configured in
routes/api.php. - Octane: Installed and running on port 8000.
User Service
- Authentication: Set up with Laravel Breeze.
- Octane: Installed and running on port 8001.
Product Service
- Model and Migration: Product model created with a migration.
- Octane: Installed and running on port 8002.
Common Errors and Fixes
Error: Connection refused when accessing services
- Cause: The service might not be running or is on a different port.
- Fix: Ensure all Octane servers are running on the correct ports.
Error: CORS policy: No 'Access-Control-Allow-Origin' header
- Cause: CORS headers not set correctly.
- Fix: Ensure the CORS middleware is correctly implemented and registered.
Error: Class 'App\Http\Middleware\Cors' not found
- Cause: Middleware not created or autoload not updated.
- Fix: Run
composer dump-autoloadto refresh the autoload files.
Conclusion
In this tutorial, we set up a basic microservices architecture using Laravel 13 Octane. We created an API Gateway with routes to manage user and product services, each running independently. This setup allows for scalable and maintainable applications, leveraging Laravel's capabilities with Octane for high performance.