百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
L

laravel-dynamodb

> 后端框架
开源

基于 DynamoDB 的 Eloquent 模型和 Laravel 查询构建器。

193 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

基于 DynamoDB 的 Eloquent 模型和 Laravel 查询构建器。

Laravel DynamoDB

A DynamoDB based Eloquent model and Query builder for Laravel.

You can find an example implementation in kitar/simplechat.

  • Motivation
  • Installation
    • Laravel
    • Non-Laravel projects
  • Sample data
  • Model
    • Extending the base model
    • Basic Usage
      • Retrieving all models
      • Retrieving a model
      • create()
      • save()
      • update()
      • delete()
      • increment() / decrement()
    • Advanced Queries
  • Authentication with model
    • Register custom user provider
    • Change auth config
  • Query Builder
    • Basic Usage
      • getItem()
      • putItem()
      • updateItem()
      • deleteItem()
    • Projection Expressions
      • select()
    • Condition Expressions
      • condition()
      • conditionIn()
      • conditionBetween()
    • Working with Queries
      • query() and keyCondition()
      • keyConditionBetween()
      • Sort order
    • Working with Scans
      • scan()
    • Filtering the Results
      • filter()
      • filterIn()
      • filterBetween()
    • Paginating the Results
      • exclusiveStartKey()
    • Using Global Secondary Indexes
      • index()
    • Atomic Counter
    • Batch Operations
      • batchGetItem()
      • batchPutItem()
      • batchDeleteItem()
      • batchWriteItem()
    • DynamoDB-specific operators for condition() and filter()
      • Comparators
      • functions
  • Debugging
  • Testing

Motivation

  • I want to use DynamoDB with Laravel. (e.g., authenticate with custom user provider)
  • I want to use a simple API which doesn't need to worry about cumbersome things like manually handling Expression Attributes.
  • I want to extend Laravel's code as much as I can to:
    • Rely on Laravel's robust codes.
    • keep the additional implementation simple and maintainable.
  • I don't want to make it fully compatible with Eloquent because DynamoDB is different from relational databases.
  • I'm longing for jessengers/laravel-mongodb. What if we have that for DynamoDB?

Installation

Install the package via Composer:

$ composer require kitar/laravel-dynamodb

Laravel (6.x, 7.x, 8.x, 9.x, 10.x, 11.x, 12.x)

Add dynamodb configs to config/database.php:

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=dynamodb

Note for Laravel 11+: Laravel 11 and later versions default to database driver 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

Non-Laravel projects

For usage outside Laravel, you can create the connection manually and start querying with Query Builder.

php
$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')->...

Sample data

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.

Model

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:

  • Eloquent model
    • Can handle relations.
    • Forward calls to model (Eloquent) query builder. (e.g., create, createOrFirst where with)
  • DynamoDB model
    • Cannot handle relations.
    • Forward calls to database (DynamoDB) query builder. (e.g., getItem, putItem, scan, filter)

Extending the base model

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:

php
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:

php
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.

php
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\Authenticatable and using Illuminate\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.

Basic Usage

Retrieving all models

php
$products = ProductCatalog::scan();

or alternatively,

php
$products = ProductCatalog::all();

You also can override the scan() method to fit your needs, such as filtering models for single table design. For example:

php
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.

Retrieving a model

If the model has only partition key:

php
ProductCatalog::find(101);

If the model also has sort key:

php
Thread::find([
    'ForumName' => 'Amazon DynamoDB', // Partition key
    'Subject' => 'DynamoDB Thread 1' // Sort key
]);

If the model has sort key and sortKeyDefault is defined:

php
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:

php
public static function find($userId)
{
    return parent::find([
        'PK' => str_starts_with($userId, 'USER#') ? $userId : 'USER#'.$userId,
        'SK' => 'USER#',
    ]);
}

create()

php
$user = User::create([
    'email' => '[email protected]',
    'type' => 'profile' // Sort key. If we don't specify this, sortKeyDefault will be used.
]);

save()

php
$user = new User([
    'email' => '[email protected]',
    'type' => 'profile'
]);

$user->save();
php
$user->name = 'foo';
$user->save();

update()

php
$user->update([
    'name' => 'foobar'
]);

delete()

php
$user->delete();

increment() / decrement()

When we call increment() and decrement(), the Atomic Counter will be used under the hood.

php
$user->increment('views', 1);
$user->decrement('views', 1);

We can also pass additional attributes to update.

php
$user->increment('views', 1, [
    'last_viewed_at' => '...',
]);

Advanced Queries

We can use Query Builder functions through model such as query scan filter condition keyCondition etc.

For example:

php
Thread::keyCondition('ForumName', '=', 'Amazon DynamoDB')
    ->keyCondition('Subject', 'begins_with', 'DynamoDB')
    ->filter('Views', '=', 0)
    ->query();

Please refer to Query Builder for the details.

Authentication with model

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.

Register custom user provider

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.

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
        );
    });
}

Change auth config

Then specify driver and model name for authentication in config/auth.php.

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.

Registration Controller

You might need to modify the registration controller. For example, if we use Laravel Starter Kits, the modificati

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

PHPawsdynamodbeloquentlaravel

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类后端框架
定价开源

> 相关工具

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架