A DynamoDB based Eloquent model and Query builder for Laravel.
A DynamoDB based Eloquent model and Query builder for Laravel.
A DynamoDB based Eloquent model and Query builder for Laravel.
You can find an example implementation in kitar/simplechat.
Install the package via Composer:
$ composer require kitar/laravel-dynamodbAdd dynamodb configs to config/database.php:
'connections' => [
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'token' => env('AWS_SESSION_TOKEN', null),
'endpoint' => env('DYNAMODB_ENDPOINT', null),
'prefix' => '', // table prefix
],
...
],Update the DB_CONNECTION variable in your .env file:
DB_CONNECTION=dynamodbNote for Laravel 11+: Laravel 11 and later versions default to
databasedriver for session, cache, and queue, which are not compatible with this DynamoDB package. You'll need to configure these services to use alternative drivers. For instance:SESSION_DRIVER=file CACHE_STORE=file QUEUE_CONNECTION=sync
For usage outside Laravel, you can create the connection manually and start querying with Query Builder.
$connection = new Kitar\Dynamodb\Connection([
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'token' => env('AWS_SESSION_TOKEN', null),
'endpoint' => env('DYNAMODB_ENDPOINT', null),
'prefix' => '', // table prefix
]);
$connection->table('your-table')->...Many of the example codes in this document are querying to DynamoDB's official sample data. If you want to try these codes with actual DynamoDB tables, it's handy to load them to your tables before.
DynamoDB model extends Eloquent model so that we can use familiar features such as mutators, serialization, etc.
The main difference between Eloquent model and DynamoDB model is:
create, createOrFirst where with)getItem, putItem, scan, filter)Most of the attributes are the same as the original Eloquent model, but there are few DynamoDB-specific attributes.
| Name | Required | Description |
|---|---|---|
| table | yes | Name of the Table. |
| primaryKey | yes | Name of the Partition Key. |
| sortKey | Name of the Sort Key. | |
| sortKeyDefault | Default value for the Sort Key. |
For example, if our table has only partition key, the model will look like this:
use Kitar\Dynamodb\Model\Model;
class ProductCatalog extends Model
{
protected $table = 'ProductCatalog';
protected $primaryKey = 'Id';
protected $fillable = ['Id', 'Price', 'Title'];
}If our table also has sort key:
use Kitar\Dynamodb\Model\Model;
class Thread extends Model
{
protected $table = 'Thread';
protected $primaryKey = 'ForumName';
protected $sortKey = 'Subject';
protected $fillable = ['ForumName', 'Subject'];
}If we set sortKeyDefault, it will be used when we instantiate or call find without sort key.
use Kitar\Dynamodb\Model\Model;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
class User extends Model implements AuthenticatableContract
{
use Authenticatable;
protected $table = 'User';
protected $primaryKey = 'email';
protected $sortKey = 'type';
protected $sortKeyDefault = 'profile';
protected $fillable = [
'name', 'email', 'password', 'type',
];
}Note that this model is implementing
Illuminate\Contracts\Auth\Authenticatableand usingIlluminate\Auth\Authenticatable. This is optional, but if we use them, we can use this model with authentication as well. For authentication, please refer to Authentication section) for more details.
$products = ProductCatalog::scan();or alternatively,
$products = ProductCatalog::all();You also can override the scan() method to fit your needs, such as filtering models for single table design. For example:
public static function scan($exclusiveStartKey = null, $sort = 'asc', $limit = 50)
{
return static::index('GSI1')
->keyCondition('GSI1PK', '=', 'PRODUCT#')
->keyCondition('GSI1SK', 'begins_with', 'PRODUCT#')
->exclusiveStartKey($exclusiveStartKey)
->scanIndexForward($sort == 'desc' ? false : true)
->limit($limit)
->query();
}DynamoDB can only handle result set up to 1MB per call, so we have to paginate if there are more results. see Paginating the Results for more details.
If the model has only partition key:
ProductCatalog::find(101);If the model also has sort key:
Thread::find([
'ForumName' => 'Amazon DynamoDB', // Partition key
'Subject' => 'DynamoDB Thread 1' // Sort key
]);If the model has sort key and sortKeyDefault is defined:
User::find('[email protected]'); // Partition key. sortKeyDefault will be used for Sort key.You also can modify the behavior of the find() method to fit your needs. For example:
public static function find($userId)
{
return parent::find([
'PK' => str_starts_with($userId, 'USER#') ? $userId : 'USER#'.$userId,
'SK' => 'USER#',
]);
}$user = User::create([
'email' => '[email protected]',
'type' => 'profile' // Sort key. If we don't specify this, sortKeyDefault will be used.
]);$user = new User([
'email' => '[email protected]',
'type' => 'profile'
]);
$user->save();$user->name = 'foo';
$user->save();$user->update([
'name' => 'foobar'
]);$user->delete();When we call increment() and decrement(), the Atomic Counter will be used under the hood.
$user->increment('views', 1);
$user->decrement('views', 1);We can also pass additional attributes to update.
$user->increment('views', 1, [
'last_viewed_at' => '...',
]);We can use Query Builder functions through model such as query scan filter condition keyCondition etc.
For example:
Thread::keyCondition('ForumName', '=', 'Amazon DynamoDB')
->keyCondition('Subject', 'begins_with', 'DynamoDB')
->filter('Views', '=', 0)
->query();Please refer to Query Builder for the details.
We can create a Custom User Provider to authenticate with DynamoDB. For the detail, please refer to Laravel's official document.
To use authentication with the model, the model should implement Illuminate\Contracts\Auth\Authenticatable contract. In this section, we'll use the example User model above.
After we prepare authenticatable model, we need to make the custom user provider. We can make it own (it's simple), but we'll use Kitar\Dynamodb\Model\AuthUserProvider in this section.
To register custom user provider, add codes below in App/Providers/AuthServiceProvider.php.
use Kitar\Dynamodb\Model\AuthUserProvider;
...
public function boot()
{
$this->registerPolicies();
Auth::provider('dynamodb', function ($app, array $config) {
return new AuthUserProvider(
$app['hash'],
$config['model'],
$config['api_token_name'] ?? null,
$config['api_token_index'] ?? null
);
});
}Then specify driver and model name for authentication in config/auth.php.
'providers' => [
// Eloquent
// 'users' => [
// 'driver' => 'eloquent',
// 'model' => App\User::class,
// ],
// DynamoDB
'users' => [
'driver' => 'dynamodb',
'model' => App\User::class,
'api_token_name' => 'api_token',
'api_token_index' => 'api_token-index'
],
],api_token_name and api_token_index are optional, but we need them if we use api token authentication.
You might need to modify the registration controller. For example, if we use Laravel Starter Kits, the modificati
No open issues yet, or sync has not completed.