PHPackages                             shailesh-matariya/laravel-spanner - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. shailesh-matariya/laravel-spanner

ActiveLibrary[Database &amp; ORM](/categories/database)

shailesh-matariya/laravel-spanner
=================================

Laravel database driver for Google Cloud Spanner

v3.5.0(5y ago)05Apache-2.0PHPPHP &gt;=7.1

Since Feb 20Pushed 5y agoCompare

[ Source](https://github.com/shailesh-matariya/laravel-spanner)[ Packagist](https://packagist.org/packages/shailesh-matariya/laravel-spanner)[ RSS](/packages/shailesh-matariya-laravel-spanner/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (8)Versions (11)Used By (0)

laravel-spanner
===============

[](#laravel-spanner)

Laravel database driver for Google Cloud Spanner

[![License](https://camo.githubusercontent.com/50fcf6f596e66a43c9e14c26e0e04af62044914c195fcc3326e732d8229042de/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f636f6c6f706c2f6c61726176656c2d7370616e6e65722e7376673f7374796c653d666c61742d737175617265)](https://github.com/colopl/laravel-spanner/blob/master/LICENSE)[![Latest Stable Version](https://camo.githubusercontent.com/a74add671c4a05a1df0316986d9c66983e27948299f00af4a6aab84b0f4522b4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636f6c6f706c2f6c61726176656c2d7370616e6e65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/colopl/laravel-spanner)[![Minimum PHP Version](https://camo.githubusercontent.com/59ce68c8e8232c6673fc99f60207fece550fa8b4f6b91e761b47d865dbe4a028/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f636f6c6f706c2f6c61726176656c2d7370616e6e65722e7376673f7374796c653d666c61742d737175617265)](https://secure.php.net/)

[![CI Status on master](https://camo.githubusercontent.com/6fd2815d4497a9b631662e99e2165b0de135b6056756038c56aceaba2e0b6edc/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f636f6c6f706c2f6c61726176656c2d7370616e6e65722f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/colopl/laravel-spanner)

Requirements
------------

[](#requirements)

- PHP &gt;= 7.1
- Laravel &gt;= 5.5
- [gRPC extension](https://cloud.google.com/php/grpc)
- [protobuf extension](https://cloud.google.com/php/grpc#install_the_protobuf_runtime_library) (not required, but strongly recommended)

Installation
------------

[](#installation)

Put JSON credential file path to env variable: `GOOGLE_APPLICATION_CREDENTIALS`

```
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json

```

Install via composer

```
composer require colopl/laravel-spanner
```

Add connection config to `config/database.php`

```
[
    'connections' => [
        'spanner' => [
            'driver' => 'spanner',
            'instance' => '',
            'database' => '',
        ]
    ]
];
```

That's all. You can use database connection as usual.

```
$conn = DB::connection('spanner');
$conn->...
```

Additional Configurations
-------------------------

[](#additional-configurations)

You can pass `SpannerClient` config and `CacheSessionPool` options as below. For more information, please see [Google Client Library docs](http://googleapis.github.io/google-cloud-php/#/docs/google-cloud/latest/spanner/spannerclient?method=__construct)

```
[
    'connections' => [
        'spanner' => [
            'driver' => 'spanner',
            'instance' => '',
            'database' => '',

            // Spanner Client configurations
            'client' => [
                'projectId' => 'xxx',
                ...
            ],

            // CacheSessionPool options
            'session_pool' => [
                'minSessions' => 10,
                'maxSessions' => 500,
            ],
        ]
    ]
];
```

Unsupported features
--------------------

[](#unsupported-features)

- STRUCT data types
- Explicit Read-only transaction (snapshot)

Limitations
-----------

[](#limitations)

### Migrations

[](#migrations)

Most functions of `SchemaBuilder` (eg, `Schema` facade, and `Blueprint`) can be used. However, `artisan migrate` command does not work since AUTO\_INCREMENT does not exist in Google Cloud Spanner.

### Eloquent

[](#eloquent)

Most functions of [Eloquent](https://laravel.com/docs/5.7/eloquent) can be used. However, some functions are not available. For example, `belongsToMany` relationship is not available.

If you use interleaved keys, you MUST define them in the `interleaveKeys` property or you won't be able to save. For more detailed instructions, see `Colopl\Spanner\Tests\Eloquent\ModelTest`.

Additional Information
----------------------

[](#additional-information)

### Transactions

[](#transactions)

Google Cloud Spanner sometimes requests transaction retries (e.g. `UNAVAILABLE`, and `ABORTED`), even if the logic is correct. For that reason, please do not manage transactions manually.

You should always use the `transaction` method which handles retry requests internally.

```
// BAD: Do not use transactions manually!!
try {
    DB::beginTransaction();
    ...
    DB::commit();
} catch (\Throwable $ex) {
    DB::rollBack();
}

// GOOD: You should always use transaction method
DB::transaction(function() {
    ...
});
```

Google Cloud Spanner creates transactions for all data operations even if you do not explicitly create transactions.

In particular, in the SELECT statement, the type of transaction varies depending on whether it is explicit or implicit.

```
// implicit transaction (Read-only transaction)
$conn->select('SELECT ...');

// explicit transaction (Read-write transaction)
$conn->transaction(function() {
    $conn->select('SELECT ...');
});

// implicit transaction (Read-write transaction)
$conn->insert('INSERT ...');

// explicit transaction (Read-write transaction)
$conn->transaction(function() {
    $conn->insert('INSERT ...');
});
```

Transaction type**SELECT** statement**INSERT/UPDATE/DELETE** statementimplicit transaction**Read-only** transaction with **singleUse** option**Read-write** transaction with **singleUse** optionexplicit transaction**Read-write** transaction**Read-write** transactionFor more information, see [Cloud Spanner Documentation about transactions](https://cloud.google.com/spanner/docs/transactions)

### Stale reads

[](#stale-reads)

You can use [Stale reads (timestamp bounds)](https://cloud.google.com/spanner/docs/timestamp-bounds) as below.

```
// There are four types of timestamp bounds: ExactStaleness, MaxStaleness, MinReadTimestamp and ReadTimestamp.
$timestampBound = new ExactStaleness(10);

// by Connection
$connection->selectWithTimestampBound('SELECT ...', $bindings, $timestampBound);

// by Query Builder
$queryBuilder
    ->withStaleness($timestampBound)
    ->get();
```

Stale reads always runs as read-only transaction with `singleUse` option. So you can not run as read-write transaction.

### Data Types

[](#data-types)

Some data types of Google Cloud Spanner does not have corresponding built-in type of PHP. You can use following classes by [Google Cloud PHP Client](https://github.com/googleapis/google-cloud-php)

- DATE: `Google\Cloud\Spanner\Date`
- BYTES: `Google\Cloud\Spanner\Bytes`
- TIMESTAMP: `Google\Cloud\Spanner\Timestamp`

`Google\Cloud\Spanner\Timestamp` is a DateTime representation with UTC timezone and nanoseconds. In laravel-spanner QueryBuilder converts `Timestamp` in the fetched rows to [Carbon](https://laravel.com/api/6.x/Illuminate/Support/Carbon.html) with the default timezone in PHP.

Note that if you execute a query without QueryBuilder, it will not have a conversion to Carbon.

### Partitioned DML

[](#partitioned-dml)

You can run partitioned DML as below.

```
// by Connection
$connection->runPartitionedDml('UPDATE ...');

// by Query Builder
$queryBuilder->partitionedUpdate($values);
$queryBuilder->partitionedDelete($values);
```

However, Partitioned DML has some limitations. See [Cloud Spanner Documentation about Partitioned DML](https://cloud.google.com/spanner/docs/dml-partitioned#dml_and_partitioned_dml) for more information.

### Interleave

[](#interleave)

You can define [interleaved tables](https://cloud.google.com/spanner/docs/schema-and-data-model#creating_a_hierarchy_of_interleaved_tables) as below.

```
$schemaBuilder->create('user_items', function (Blueprint $table) {
    $table->uuid('user_id');
    $table->uuid('id');
    $table->uuid('item_id');
    $table->integer('count');
    $table->timestamps();

    $table->primary(['user_id', 'id']);

    // interleaved table
    $table->interleave('users')->onDelete('cascade');

    // interleaved index
    $table->index(['userId', 'created_at'])->interleave('users');
});
```

### Mutations

[](#mutations)

You can [insert, update, and delete data using mutations](https://cloud.google.com/spanner/docs/modify-mutation-api) to modify data instead of using DML to improve performance.

```
$queryBuilder->insertUsingMutation($values);
$queryBuilder->updateUsingMutation($values);
$queryBuilder->deleteUsingMutation($values);

```

Please note that mutation api does not work the same way as DML. All mutations calls within a transaction are queued and sent as batch at the time you commit. This means that if you make any modifications through the above functions and then try to SELECT the same records before committing, the returned results will not include any of the modifications you've made inside the transaction.

### SessionPool and AuthCache

[](#sessionpool-and-authcache)

In order to improve the performance of the first connection per request, we use [AuthCache](https://github.com/googleapis/google-cloud-php#caching-access-tokens) and [CacheSessionPool](https://googleapis.github.io/google-cloud-php/#/docs/google-cloud/latest/spanner/session/cachesessionpool).

By default, laravel-spanner uses [Filesystem Cache Adapter](https://symfony.com/doc/current/components/cache/adapters/filesystem_adapter.html) as the caching pool. If you want to use your own caching pool, you can extend ServiceProvider and inject it into the constructor of `Colopl\Spanner\Connection`.

### Laravel Tinker

[](#laravel-tinker)

You can use [Laravel Tinker](https://github.com/laravel/tinker) with commands such as `php artisan tinker`. But your session may hang when accessing Cloud Spanner. This is known gRPC issue that occurs when PHP forks a process. The workaround is to add following line to `php.ini`.

```
grpc.enable_fork_support=1
```

Development
-----------

[](#development)

### Testing

[](#testing)

You can run tests on docker by the following command. Note that some environment variables must be set. In order to set the variables, rename [.env.sample](./.env.sample) to `.env` and edit the values of the defined variables.

NameValue`GOOGLE_APPLICATION_CREDENTIALS`The path of the service account key file with access privilege to Google Cloud Spanner instance`DB_SPANNER_INSTANCE_ID`Instance ID of your Google Cloud Spanner`DB_SPANNER_DATABASE_ID`Name of the database with in the Google Cloud Spanner instance`DB_SPANNER_PROJECT_ID`Not required if your credential includes the project ID```
make test
```

License
-------

[](#license)

Apache 2.0 - See [LICENSE](./LICENSE) for more information.

###  Health Score

26

—

LowBetter than 41% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 52.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~73 days

Recently: every ~96 days

Total

8

Last Release

2173d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/19707310?v=4)[Shailesh Matariya](/maintainers/shailesh-matariya)[@shailesh-matariya](https://github.com/shailesh-matariya)

---

Top Contributors

[![castaneai](https://avatars.githubusercontent.com/u/562795?v=4)](https://github.com/castaneai "castaneai (20 commits)")[![taka-oyama](https://avatars.githubusercontent.com/u/748854?v=4)](https://github.com/taka-oyama "taka-oyama (15 commits)")[![erjanmx](https://avatars.githubusercontent.com/u/4899432?v=4)](https://github.com/erjanmx "erjanmx (1 commits)")[![MatthewHallCom](https://avatars.githubusercontent.com/u/1230091?v=4)](https://github.com/MatthewHallCom "MatthewHallCom (1 commits)")[![shailesh-matariya](https://avatars.githubusercontent.com/u/19707310?v=4)](https://github.com/shailesh-matariya "shailesh-matariya (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/shailesh-matariya-laravel-spanner/health.svg)

```
[![Health](https://phpackages.com/badges/shailesh-matariya-laravel-spanner/health.svg)](https://phpackages.com/packages/shailesh-matariya-laravel-spanner)
```

###  Alternatives

[shopware/platform

The Shopware e-commerce core

3.4k1.5M3](/packages/shopware-platform)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

585.6M574](/packages/shopware-core)[statamic/cms

The Statamic CMS Core Package

4.8k3.6M987](/packages/statamic-cms)[leantime/leantime

Open source project management system for non-project managers. Simple like Trello, powerful like Jira. Built with neurodiversity in mind.

10.2k3.5k](/packages/leantime-leantime)[statamic-rad-pack/runway

Eloquently manage your database models in Statamic.

135224.7k7](/packages/statamic-rad-pack-runway)[markocupic/calendar-event-booking-bundle

Contao Calendar Event Booking Bundle

135.2k1](/packages/markocupic-calendar-event-booking-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
