Laravel
DynamoDB
AWS
Database Integration
PHP Development

how to use dynamo db with laravel?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

Amazon DynamoDB is a NoSQL database service that offers fast and predictable performance with seamless scalability. Leveraging DynamoDB with Laravel—one of the most popular PHP frameworks—can empower developers to build highly scalable and performant applications. This article will guide you through the steps to integrate DynamoDB with Laravel, providing explanations, code snippets, and examples.

Prerequisites

Before you start, ensure you have the following:

  • A Laravel application set up. You can create one using Composer.
  • An AWS account.
  • Basic understanding of Laravel and AWS services.

Installation and Configuration

Step 1: Install the AWS SDK for PHP

To interact with AWS services, you need to install the AWS SDK for PHP. You can add it to your Laravel project using Composer:

bash
composer require aws/aws-sdk-php

Step 2: Configure AWS Credentials

Create an IAM user via the AWS Management Console and grant it permissions to access DynamoDB. Then, configure your credentials using the AWS CLI or by editing the ~/.aws/credentials file directly:

ini
[default]
aws_access_key_id = YOUR_AWS_ACCESS_KEY_ID
aws_secret_access_key = YOUR_AWS_SECRET_ACCESS_KEY

Alternatively, you can create environment variables in your Laravel .env file:

plaintext
AWS_ACCESS_KEY_ID=your-access-key-id
AWS_SECRET_ACCESS_KEY=your-secret-access-key
AWS_DEFAULT_REGION=us-west-2

Step 3: Laravel Configuration

In the config/services.php file, add your AWS configuration:

php
1return [
2
3    // Other service configuration...
4
5    'dynamodb' => [
6        'key'    => env('AWS_ACCESS_KEY_ID'),
7        'secret' => env('AWS_SECRET_ACCESS_KEY'),
8        'region' => env('AWS_DEFAULT_REGION', 'us-west-2'),
9    ],
10];

Using DynamoDB with Laravel

Step 1: Create a DynamoDB Client Instance

First, create an instance of the DynamoDB client in AWS SDK:

php
1use Aws\DynamoDb\DynamoDbClient;
2
3$client = new DynamoDbClient([
4    'region'  => config('services.dynamodb.region'),
5    'version' => 'latest',
6    'credentials' => [
7        'key'    => config('services.dynamodb.key'),
8        'secret' => config('services.dynamodb.secret'),
9    ]
10]);

Step 2: Create a DynamoDB Table

You can define a table schema in DynamoDB. For demonstration, we'll create a simple products table with a primary key:

php
1$tableName = 'products';
2
3$result = $client->createTable([
4    'TableName' => $tableName,
5    'AttributeDefinitions' => [
6        [
7            'AttributeName' => 'ProductId',
8            'AttributeType' => 'S'
9        ]
10    ],
11    'KeySchema' => [
12        [
13            'AttributeName' => 'ProductId',
14            'KeyType' => 'HASH'
15        ]
16    ],
17    'ProvisionedThroughput' => [
18        'ReadCapacityUnits' => 5,
19        'WriteCapacityUnits' => 5
20    ]
21]);
22
23$client->waitUntil('TableExists', ['TableName' => $tableName]);

Step 3: CRUD Operations

Create Item

To insert an item into the products table:

php
1use Aws\DynamoDb\Exception\DynamoDbException;
2use Aws\DynamoDb\Marshaler;
3
4$marshaler = new Marshaler();
5
6$item = $marshaler->marshalItem([
7    'ProductId' => '123',
8    'Name' => 'Laptop',
9    'Price' => 999
10]);
11
12try {
13    $result = $client->putItem([
14        'TableName' => 'products',
15        'Item' => $item
16    ]);
17    echo "Item created successfully.\n";
18} catch (DynamoDbException $e) {
19    echo "Unable to add item:\n";
20    echo $e->getMessage() . "\n";
21}

Read Item

To read an item from the products table:

php
1$key = $marshaler->marshalJson(json_encode(['ProductId' => '123']));
2
3try {
4    $result = $client->getItem([
5        'TableName' => 'products',
6        'Key' => $key
7    ]);
8
9    echo "Item retrieved:\n";
10    print_r($result['Item']);
11} catch (DynamoDbException $e) {
12    echo "Unable to get item:\n";
13    echo $e->getMessage() . "\n";
14}

Update Item

To update an item:

php
1try {
2    $result = $client->updateItem([
3        'TableName' => 'products',
4        'Key' => $key,
5        'UpdateExpression' => 'set Price = :p',
6        'ExpressionAttributeValues' => [
7            ':p' => ['N' => '1099']
8        ],
9        'ReturnValues' => 'UPDATED_NEW'
10    ]);
11
12    echo "Item updated:\n";
13    print_r($result);
14} catch (DynamoDbException $e) {
15    echo "Unable to update item:\n";
16    echo $e->getMessage() . "\n";
17}

Delete Item

To delete an item:

php
1try {
2    $result = $client->deleteItem([
3        'TableName' => 'products',
4        'Key' => $key
5    ]);
6
7    echo "Item deleted:\n";
8    print_r($result);
9} catch (DynamoDbException $e) {
10    echo "Unable to delete item:\n";
11    echo $e->getMessage() . "\n";
12}

Error Handling and Best Practices

Error Handling

Handle exceptions with AWS SDK:

php
1catch (DynamoDbException $e) {
2    // Log error
3    // Return formatted error message
4}

Best Practices

  • Use environment variables to store sensitive data.
  • Monitor the provisioned throughput to optimize cost and performance.
  • Implement data validation when reading or writing to the database.

Summary Table

Key PointDescription
InstallationInstall AWS SDK and configure AWS credentials.
ConfigurationConfigure services.php with the AWS details.
Table CreationUse createTable() with attributes, key schema, and throughput settings.
CRUD OperationsPerform putItem, getItem, updateItem, and deleteItem using DynamoDB client.
Error HandlingUse DynamoDbException for error management; log and handle exceptions appropriately.
Best PracticesUse environment variables, monitor throughput, and validate data.

Conclusion

Integrating Amazon DynamoDB with Laravel allows you to harness the power of AWS's scalable database service while utilizing Laravel's expressive coding capabilities. Following the steps outlined in this article will enable you to build applications that are not only scalable but also maintainable and easy to understand.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.