Laravel DynamoDB Eloquent Models and Query Builder

Packages

April 5th, 2022

Laravel DynamoDB Eloquent Models and Query Builder

Laravel DynamoDB is a DynamoDB-based Eloquent model and Query builder for Laravel. Using the provided Dynamo driver, models extend the Eloquent base model:

1use Kitar\Dynamodb\Model\Model;
2 
3class ProductCatalog extends Model
4{
5 // Required
6 protected $table = 'ProductCatalog';
7 
8 // Name of the partition key (required)
9 protected $primaryKey = 'Id';
10 
11 // Name of the sort key (optional)
12 protected $sortKey = 'Subject';
13 
14 // Default sort key value when we
15 // call find without a sort key.
16 protected $sortKeyDefault = 'profile';
17 
18 protected $fillable = ['Id', 'Price', 'Title'];
19}

Here are a few examples from the readme of queries and operations you can expect using this package:

1// Get all models
2$products = ProductCatalog::scan();
3// or
4$products = ProductCatalog::all();
5 
6// Paginated
7$products = ProductCatalog::limit(5)->scan();
8 
9// Creating a user
10$user = User::create([
11 'email' => 'foo@bar.com',
12 // Sort key. If we don't specify this,
13 // sortKeyDefault will be used.
14 'type' => 'profile',
15]);
16 
17// Instantiate a model and then save.
18$user = new User([
19 'email' => 'foo@bar.com',
20 'type' => 'profile'
21]);
22 
23$user->save();
24 
25// Update an existing model
26$user->update([
27 'name' => 'foobar'
28]);

This package includes more advanced usage of Dynamo, including a query builder that you can use without models (and outside of Laravel too). Also, the query builder supports things such as Condition Expressions. For example:

1DB::table('ProductCatalog')
2 ->condition('Id', 'attribute_not_exists')
3 ->orCondition('Price', 'attribute_not_exists')
4 ->putItem([/*...*/]);

Here's an example of filter expressions, which can filter results with expressions before results are returned from the database:

1$response = DB::table('Thread')
2 ->filter('LastPostedBy', '=', 'User A')
3 ->scan();
4 
5// orFilter()
6$response = DB::table('Thread')
7 ->filter('LastPostedBy', '=', 'User A')
8 ->orFilter('LastPostedBy', '=', 'User B')
9 ->scan();
10 
11// filterIn
12$response = DB::table('Thread')
13 ->filterIn('LastPostedBy', ['User A', 'User B'])
14 ->scan();
15 
16// filterBetween
17$response = DB::table('ProductCatalog')
18 ->filterBetween('Price', [0, 100])
19 ->scan();

The Laravel DynamoDB package also has detailed instructions on using a DynamoDB model for user authentication. You can learn more about this package, get full installation instructions, and view the source code on GitHub.


This package was submitted to our Laravel News Links section. Links is a place the community can post packages and tutorials around the Laravel ecosystem. Follow along on Twitter @LaravelLinks

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.