- Learn to build a REST API in PHP using Laravel and Couchbase
- Explore key-based operations and SQL++ querying using PHP SDK
- Explore CRUD operations in action with Couchbase
Come iniziare
Prerequisiti
Per eseguire questo progetto preconfigurato, avrete bisogno di:
- Couchbase Capella cluster with Travel-sample La carretta è carica.
- Per eseguire questo tutorial utilizzando un cluster di Couchbase gestito autonomamente, si prega di consultare la documentazione relativa al comando appendice.
- PHP 8.2 or higher installed
- Ensure that the PHP version is compatibile con il SDK di Couchbase.
- Code Editor installed (Visual Studio Code, PhpStorm, or Sublime Text)
- Composer command line
Source Code
git clone https://github.com/couchbase-examples/php-laravel-quickstart.git
Change Directory
cd php-laravel-quickstart
Installare le dipendenze
cd php-laravel-quickstart
composer install
Note: Composer automatically installs the required dependencies when building the project.
Initial Configuration
After installing dependencies, you need to set up the basic Laravel configuration:
- Create the environment file:
cp .env.example .env
- Generate application key:
php artisan key:generate
Couchbase Service Provider
Il CouchbaseServiceProvider class is a Laravel service provider class responsible for setting up the connection to a Couchbase database in a Laravel application.
Application Environment
All configuration for communication with the database is read from environment variables. As a security best practice, you should set these values in your .env file:
DB_CONN_STR=<connection_string>
DB_USERNAME=<username>
DB_PASSWORD=<password>
DB_BUCKET=travel-sample
Replace the placeholder values with your actual Couchbase cluster details.
The connection string should be in the following format:
return [
'host' => env('DB_CONN_STR', 'couchbase://127.0.0.1'),
'username' => env('DB_USERNAME', 'Administrator'),
'password' => env('DB_PASSWORD', 'password'),
'bucket' => env('DB_BUCKET', 'travel-sample'),
];
For more information on the Laravel connection string, see the Database Configuration documentazione.
Running The Application
Directly on the machine
At this point the application is ready, and you can run it via the command line:
php artisan serve
Note: Either the Couchbase Server must be installed and running on localhost or the connection string must be updated in the
config/couchbase.phpfile.
Tip: If Swagger UI loads without endpoints, generate the docs:
php artisan l5-swagger:generate
Docker
Creare l'immagine Docker
docker build -t php-laravel-quickstart .
Iniziare a eseguire l'immagine Docker
docker run -d --name laravel-container -p 8000:8000
-e DB_CONN_STR=<connection_string>
-e DB_USERNAME=<username>
-e DB_PASSWORD=<password>
-e DB_BUCKET=travel-sample
php-laravel-quickstart
Note: Environment variables passed to the Docker container will override the default values in the configuration.
Once the application is running, you can access it in your browser at http://localhost:8000. Swagger UI is available at http://localhost:8000/api/documentation.
Verificare l'applicazione
Una volta avviata l'applicazione, è possibile visualizzare i dettagli dell'applicazione nei log.

L'applicazione verrà eseguita sul port 8000 del vostro computer locale (http://localhost:8000). Open Swagger UI at http://localhost:8000/api/documentation to try the API endpoints. Swagger documentation is used in this demo to showcase the different API endpoints and how they can be invoked. More details on the Swagger documentation can be found in the appendice.

Modello dei dati
Per questo tutorial utilizzeremo tre collezioni:, aeroporto, aerolinea e itinerario that contain sample airports, airlines and airline routes respectively. The route collection connects the airports and airlines as seen in the figure below. We use these connections in the quickstart to generate airports that are directly connected and airlines connecting to a destination airport. Note that these are just examples to highlight how you can use SQL queries to join the collections.

Struttura dei documenti dell'aerolinea
We will be setting up a REST API to manage some airline documents. The nome field is the name of the airline. The callsign field is the callsign of the airline. The iata field is the IATA code of the airline. The icao field is the ICAO code of the airline. The paese field is the country of the airline.
Our airline document will have a structure similar to the following example:
{
"name": "Couchbase Airways",
"callsign": "Couchbase",
"iata": "CB",
"icao": "CBA",
"country": "United States"
}
Struttura del codice
Project Structure
.
├── app/
│ ├── Http/
│ │ └── Controllers/
│ │ ├── AirlineController.php
│ │ ├── AirportController.php
│ │ ├── RouteController.php
│ │ └── HotelController.php
│ ├── Models/
│ │ ├── Airline.php
│ │ ├── Airport.php
│ │ ├── Route.php
│ │ └── Hotel.php
│ └── Providers/
│ └── CouchbaseServiceProvider.php
├── config/
│ └── couchbase.php
├── routes/
│ └── api.php
└── tests/
└── Feature/
├── AirlineTest.php
├── AirportTest.php
├── RouteTest.php
└── HotelTest.php
Key Components
- Controllers: Handle HTTP requests and responses for each entity
- Modelli: Define data structures and business logic for Couchbase operations
- Service Provider: Configures Couchbase connection and collection references
- Tests: Integration tests for all API endpoints
Entità aerea
Per questo tutorial, ci concentreremo sull'entità dell'aerolinea per dimostrare le operazioni CRUD e le query SQL++.
We will be setting up a REST API to manage airline documents:
- POST Airline – Crea una nuova compagnia aerea
- GET Airline – Leggere la compagnia aerea specificata
- PUT Airline – Aggiornamento della compagnia aerea specificata
- Elimina l'aerolino – Cancellare la compagnia aerea
- Elenco delle compagnie aeree – Raccogli tutte le compagnie aeree. Se desideri, puoi filtrare l'elenco per paese
- Airlines to Destination – Get airlines flying to a destination airport
Per le operazioni CRUD utilizzeremo il Operazioni chiave-valore that are built into the Couchbase SDK to create, read, update, and delete a document. Every document will need an ID (similar to a primary key in other databases) to save it to the database. This ID is passed in the URL. For other endpoints, we will use SQL++ per richiedere documenti.
POST Airline
Apri AirlineController.php apri il file e naviga fino alla store method. The request data is validated and then passed to the model to save the airline document.
// store method in AirlineController.php
public function store(Request $request, $id)
{
if ($errorResponse = $this->validateRequest($request)) {
return $errorResponse;
}
try {
$data = $request->only($this->allowedAttributes);
$airline = new Airline($data);
$airline->saveAirline($id);
return response()->json(['message' => 'Airline created successfully'], 201);
} catch (Exception $e) {
return response()->json(['message' => 'Internal Server Error'], 500);
}
}
Chiamiamo il saveAirline method in the Airline model, which uses the upsert method from the Couchbase SDK. The upsert method inserts a new document or updates an existing one.
// saveAirline method in Airline model
public function saveAirline($id)
{
$data = $this->attributesToArray();
unset($data['id']);
$this->bucket->scope('inventory')->collection('airline')->upsert($id, $data);
}
GET Airline
Navigare fino alla mostra il metodo nel AirlineController.php file. This method retrieves a specific airline document using its ID.
// show method in AirlineController.php
public function show($id)
{
try {
$airline = Airline::findAirline($id);
if (!$airline) {
return response()->json(['message' => 'Airline not found'], 404);
}
return response()->json($airline);
} catch (Exception $e) {
return response()->json(['message' => 'Internal Server Error'], 500);
}
}
Chiamiamo il findAirline method in the Airline model, which uses the ottenere method from the Couchbase SDK for key-value retrieval.
// findAirline method in Airline model
public static function findAirline($id)
{
$instance = new static;
$document = $instance->bucket->scope('inventory')->collection('airline')->get($id);
$data = $document->content();
return new static($data);
}
PUT Airline
The PUT operation uses the same store method as POST, leveraging the upsert functionality to either update an existing document or create a new one if it doesn’t exist.
// Same store method handles both POST and PUT
$airline->saveAirline($id); // Uses upsert internally
Il upsert operation in Couchbase automatically handles both insert and update scenarios, making it perfect for PUT requests.
Elimina l'aerolino
Navigare fino alla distruggere il metodo nel AirlineController.php file. This method deletes an airline document by its ID.
// destroy method in AirlineController.php
public function destroy($id)
{
try {
$airline = Airline::findAirline($id);
if (!$airline) {
return response()->json(['message' => 'Airline not found'], 404);
}
Airline::destroyAirline($id);
return response()->json(['message' => 'Airline deleted successfully'], 200);
} catch (Exception $e) {
return response()->json(['message' => 'Internal Server Error'], 500);
}
}
Chiamiamo il destroyAirline method in the Airline model, which uses the rimuovere method from the Couchbase SDK.
// destroyAirline method in Airline model
public static function destroyAirline($id)
{
$instance = new static;
$instance->bucket->scope('inventory')->collection('airline')->remove($id);
}
Elenco delle compagnie aeree
Navigare fino alla indice il metodo nel AirlineController.php file. This method retrieves a list of airlines with optional country filtering and pagination.
// index method in AirlineController.php
public function index(Request $request)
{
try {
$offset = $request->query('offset', 0);
$limit = $request->query('limit', 10);
$country = $request->query('country');
$airlines = Airline::getAllAirlinesByCountry($country, $offset, $limit);
return response()->json($airlines);
} catch (Exception $e) {
return response()->json(['message' => 'Internal Server Error'], 500);
}
}
Chiamiamo il getAllAirlinesByCountry method in the Airline model, which uses SQL++ queries to retrieve filtered results.
// getAllAirlinesByCountry method in Airline model
public static function getAllAirlinesByCountry($country, $offset = 0, $limit = 10)
{
$query = "SELECT * FROM `travel-sample`.`inventory`.`airline`";
if ($country) {
$query .= " WHERE country = '$country'";
}
$query .= " LIMIT $limit OFFSET $offset";
$result = $instance->bucket->scope('inventory')->query($query);
return collect($result->rows());
}
Airlines to Destination
This endpoint demonstrates SQL++ queries with JOINs to find airlines that fly to a specific destination airport.
// getAirlinesToAirport method in Airline model
public static function getAirlinesToAirport($destinationAirportCode, $offset = 0, $limit = 10)
{
$query = "
SELECT air.callsign, air.country, air.iata, air.icao, META(air).id AS id, air.name
FROM (
SELECT DISTINCT route.airlineid AS airlineId
FROM `travel-sample`.`inventory`.`route` AS route
WHERE route.destinationairport = '$destinationAirportCode'
) AS subquery
JOIN `travel-sample`.`inventory`.`airline` AS air ON META(air).id = subquery.airlineId
LIMIT $limit OFFSET $offset";
$result = $instance->bucket->scope('inventory')->query($query);
return collect($result->rows());
}
This query demonstrates advanced SQL++ features:
- Subquery: Finds distinct airline IDs from routes to the destination
- JOIN: Connects route and airline collections
- META(): Accesses document metadata to get the document ID
Running The Tests
This command will execute all the test cases in your project.
php artisan test
Project Setup Notes
This project was based on the standard Laravel project.
A full list of packages are referenced in the composer.json file.
Contributing
Contributions are welcome! If you’d like to contribute to this project, please fork the repository and create a pull request.
Appendice
Ampliare l'API aggiungendo un'entità nuova
Se desiderate aggiungere un'altra entità alle API, seguite questi passaggi:
-
Create the new entity (collection) in the Couchbase bucket: You can create the collection using the SDK o tramite il Interfaccia del server Couchbase.
-
Define the model: Create a new model in the
app/Modelsdirectory, similar to the existingAereamodel. Note that this quickstart already includes aHotelmodel as an example. For a new entity, you would create a similar structure:namespace AppModels; use IlluminateDatabaseEloquentModel; class YourEntity extends Model { protected $bucket; protected $fillable = [ // Define your entity fields here ]; public function __construct(array $attributes = []) { parent::__construct($attributes); $this->bucket = app('couchbase.bucket'); } // Add methods for querying, saving, and deleting data } -
Define the controller: Create a new controller in the
app/Http/Controllersdirectory, similar to the existingAirlineController. For example, you can create a fileHotelController.php:namespace AppHttpControllers; use IlluminateHttpRequest; use AppModelsHotel; class HotelController extends Controller { // Add methods for handling HTTP requests for the Hotel entity } -
Define the routes: Nel
routes/api.phpfile, define the routes for the new entity similar to the existing routes for airlines:Route::prefix('v1/hotels')->group(function () { Route::get('list', 'HotelController@index'); Route::get('{id}', 'HotelController@show'); Route::post('{id}', 'HotelController@store'); Route::put('{id}', 'HotelController@update'); Route::delete('{id}', 'HotelController@destroy'); }); -
Integration tests: Create a new test class in the
tests/Featuredirectory, similar to the existing tests. For example, you can create a fileHotelIntegrationTest.php:namespace TestsFeature; use TestsTestCase; class HotelIntegrationTest extends TestCase { // Add test methods for the Hotel endpoints }
Gestione automatica di un cluster di Couchbase
If you are running this quickstart with a self-managed Couchbase cluster, you need to caricare caricare i dati del bucket dei dati di viaggio nel cluster e generare le credenziali per il bucket.
È necessario aggiornare la stringa di connessione e le credenziali nel file config/couchbase.php file:
DB_CONN_STR=couchbase://<your-couchbase-server>
DB_USERNAME=<your-username>
DB_PASSWORD=<your-password>
DB_BUCKET=travel-sample
Sostituire <your-couchbase-server>, <your-username>, e <your-password> with your actual Couchbase server details and credentials.
NOTA: Couchbase must be installed and running prior to running the Laravel app.
Documentazione Swagger
La documentazione di Swagger fornisce una panoramica chiara dell'API, includendo endpoint, metodi HTTP, parametri delle richieste e oggetti di risposta.
Fare clic su un singolo endpoint per ampliarlo e visualizzare le informazioni dettagliate. Ciò include la descrizione dell’endpoint, i possibili codici di stato delle risposte e i parametri della richiesta che esso accetta.
Testare l'API
È possibile provare un'API cliccando sul pulsante “Prova” accanto agli endpoint.
-
Parametri: Se un endpoint richiede parametri, l'interfaccia utente Swagger fornisce dei campi di input da compilare. Questi possono includere parametri di percorso, stringhe di query, intestazioni o il corpo di una richiesta POST/PUT.
-
Esecuzione: Una volta inseriti tutti i parametri necessari, è possibile cliccare sul pulsante “Esecuzione” per effettuare una chiamata API in tempo reale. L’interfaccia utente Swagger invierà la richiesta all’API e visualizzerà la risposta direttamente nella documentazione. Ciò include il codice della risposta, gli header e il corpo della risposta.
Modelli
Swagger documenta la struttura dei corpi di richiesta e risposta utilizzando modelli. Questi modelli definiscono la struttura dei dati prevista utilizzando lo schema JSON e sono estremamente utili per comprendere quali dati inviare e quali aspettarsi.