PHPackages                             julianmar/laravel-crate - 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. [API Development](/categories/api)
4. /
5. julianmar/laravel-crate

ActiveLibrary[API Development](/categories/api)

julianmar/laravel-crate
=======================

Crate.io driver for Laravel 5

v1.1(6y ago)17MITPHPPHP &gt;7.2CI failing

Since Oct 30Pushed 6y ago2 watchersCompare

[ Source](https://github.com/JulianMar/laravel-crate)[ Packagist](https://packagist.org/packages/julianmar/laravel-crate)[ RSS](/packages/julianmar-laravel-crate/feed)WikiDiscussions master Synced yesterday

READMEChangelogDependencies (6)Versions (3)Used By (0)

Crate.io driver for Laravel 6
-----------------------------

[](#crateio-driver-for-laravel-6)

This is a fork of [RatkoR](https://github.com/RatkoR/laravel-crate.io) repo. He did an amazing Job with the Driver but it is not maintained anymore

This is an Eloquent and Query builder support for Crate.io. Extends the original Laravel API with Crate PDO driver.

### Crate and Crate PDO

[](#crate-and-crate-pdo)

Crate is a distributed SQL Database based on Elasticsearch, Lucene and other goodies. See their official page on [Crate.io](https://crate.io)for more info.

Crate.io published a [PDO](https://github.com/crate/crate-pdo) and [DBAL](https://github.com/crate/crate-dbal) driver for easy access to the crate DB server. Laravel-crate.io project uses those adapters when connecting to Crate DB.

### Project status

[](#project-status)

Laravel-crate.io is used in our internal projects. We did a bunch of unit tests and the driver seems ok. We use id as a caching layer in front of our DB servers. Crate is insanely fast (Elasticsearch) and offloads our DB servers a lot.

Still, it's still early in development, so **if you find any bugs, please open an issue ticket**.

### Installation

[](#installation)

Laravel 5.5 till 6 is supported

Add a require to your composer.json :

```
    composer require julianmar/laravel-crate.io:^1.0
```

Laravel 5.5+ uses Package Auto-Discovery, so doesn't require you to manually add the ServiceProvider.

You'll have to install crate.io server, of course. See installation instructions on their site.

### Configuration

[](#configuration)

Open `config/database.php` and add new crate database connection (with config values to match your setup):

```
'crate' => array(
    'driver'   => 'crate',
    'host'     => 'localhost',
    'database' => 'doc',
    'port'     => 4200,
),
```

Next, change default database connection to `"crate"`.

```
'default' => 'crate',
```

#### Configuration for HTTP Basic Auth

[](#configuration-for-http-basic-auth)

This driver supports standard CrateDB auth methods `trust` and `password` via HTTP Basic Auth. To enable this, edit the `crate` config you created in the previous step and add `username` and `password` with appropriate values for your system.

For more information on CrateDB auth methods, see CrateDB's documentation about [Authentication Methods](https://crate.io/docs/crate/reference/en/latest/admin/auth/methods.html).

```
'crate' => array(
    'driver'      => 'crate',
    'host'        => 'localhost',
    'database'    => 'doc',
    'port'        => 4200,
    'username'    => 'MyUsername',
    'password'    => 'MyPassword',
),
```

#### Configuration for multiple hosts

[](#configuration-for-multiple-hosts)

This driver can handle conenctions to multiple crate hosts. To use them, write `host` config parameter as a comma delimited list of hosts. Like:

```
'crate' => array(
    'driver'   => 'crate',
    'host'     => 'localhost,10.0.0.1,10.0.0.2',
    'database' => 'doc',
    'port'     => 4200,
),
```

The DSN created in this case looks like:

```
'crate:localhost:4200,10.0.0.1:4200,10.0.0.2:4200'

```

If you need to specify different ports, add them to the `host` param like:

```
    'host'     => 'localhost:4201,10.0.0.1:4300,10.0.0.2',
```

which will create a DSN like:

```
'crate:localhost:4201,10.0.0.1:4300,10.0.0.2:4200'

```

**Randomization**

`crate-pdo` takes [the first host](https://github.com/crate/crate-pdo/blob/master/src/Crate/PDO/PDO.php#L87)from list of hosts. To overcome this we randomize all hosts so that connections to multiple crate servers are distributed. If you don't want randomization, add a `randomHosts` parameter and set it to `false`:

```
'crate' => array(
    'driver'   => 'crate',
    'host'     => 'localhost,10.0.0.1,10.0.0.2',
    'database' => 'doc',
    'port'     => 4200,
    'randomHosts' => false,
),
```

**Note on PDO::FETCH\_CLASS**

Crate doesn't support PDO::FETCH\_CLASS so we silently change it to PDO::FETCH\_ASSOC. This happens only for Crate connections, your normal MySQL connections will still use FETCH\_CLASS.

See more about fetch types on their [github](https://github.com/crate/crate-pdo) or [crate](https://crate.io/docs/reference/pdo/usage.html#fetch-modes) page.

### What works and what doesn't

[](#what-works-and-what-doesnt)

Crate.io supports many of the SQL statements, but not all of them. Be sure to take a look at their [site](https://crate.io/docs/stable/sql/index.html) if you're in doubt.

We're throwing an `Julianmar\Crate\NotImplementedException` for those statements that you might wrongly try to use. We tried to cover all of them, but if we missed any you'll get Exception from Crate DB.

Big things that are **not** supported are:

- joins
- subselects
- [auto increments](https://crate.io/docs/stable/sql/ddl.html#constraints) - you'll have to manage those by yourself
- whereBetween(s)
- unique indexes
- foreign keys (and relations)
- dropping, renaming columns (adding fields works)
- naming columns like \_ id, \_ version, \_ score - these are restricted, crate uses it [internally](https://crate.io/docs/stable/sql/ddl.html)

Crate specific stuff that was added is:

- object type
- array type
- index off, index plain
- fulltext indexes over single or multiple fields w/o analyzers

Also, `Article::truncate()` has been changed to silently use `delete from article`;

Note, that Crate.io does not support uppercase letters in table or schema names. See this and other restrictions [here](https://crate.io/docs/stable/sql/ddl.html#naming-restrictions).

### Schema support

[](#schema-support)

Migration and schema are supported. You can use `artisan migrate` commands to create or drop tables.

Crate has only a subset of [field types](https://crate.io/docs/stable/sql/data_types.html)(and some new ones), so choose appropriate.

Crate types:

- boolean
- string
- numeric (integer, long, short, double, float, byte)
- ip, geo\_point (still have to implement these two)
- timestamp
- object
- array

Some SQL types are silently linked to crate types. For example, `bigInteger` is linked to `long`, `text, mediumtext, longtext, enum` are linked to `string`, ...

An example of schema in migration file would be:

```
        Schema::create('article', function(Blueprint $table)
        {
            $table->integer('id');

            $table->string('title')->index('plain');
            $table->mediumText('summary');
            $table->text('internal_Comment')->index('off');
            $table->text('body')->index('fulltext:english');
            $table->bigInteger('nb_views');
            $table->timestamp('published_on');

            $table->arrayField('images','object as (id integer, title string');
            $table->objectField('author','(dynamic) as (id integer, name string)');

            $table->timestamps();

            $table->primary('id');
        });
```

#### Blob tables

[](#blob-tables)

Creating (and dropping) blob tables is also supported. Blob tables don't have arbitrary colums, just digest and last\_moified. And even these are created automatically.

An example of create blob schema is:

```
        Schema::createBlob('myblob');
```

*There is no need for the callback parameter (the second parameter in createBlob() which defines fields). If you pass it it will be silently ignored.*

To drop a table in schema do:

```
    Schema::dropBlob('myblob');
```

#### Description of some SQL/Crate schema differences

[](#description-of-some-sqlcrate-schema-differences)

**Fulltext index on a single field can be added as:**

```
$table->index('field1','fulltext');
```

or

```
$table->string('field1')->index('fulltext');
```

**Fulltext index on multiple fields:**

```
$table->index(['field1','field2'],'fulltext');
```

**Fulltext index with english analyzer on multiple fields:**

```
$table->index(['field1','field2'],'fulltext:english');
```

**Primary key on single field:**

```
$table->primary('field1');
```

**Primary key on multiple fields:**

```
$table->primary(['f_id','f2_id']);
```

**To not include a field in default index**

```
$table->string('not_important_field')->index('off');
```

**A PLAIN index (the default index)**

```
$table->string('field')->index('plain');
```

or

```
$table->string('field')->index();
```

or just leave it out, crate will index it.

**To drop a table in migration scripts:**

```
Schema::drop('article');
```

**To add an 'object' field use:**

```
$table->objectField('field_name', 'object parameters');
```

where `object parameters` can be any parameters that crate excepts for an object. See their [documentation](https://crate.io/docs/stable/sql/data_types.html#object)for objects. Examples would be:

```
$table->objectField('my_object_1','as (f_date timestamp)');
$table->objectField('my_object_2','as (object(dynamic) as (name string, birthday timestamp)');
```

**Add an 'array' field:**

Arrays are added with `->arrayField('name', 'array parameters')`. As is with `object` type, `array paramters` can have any property that crate allows for arrays. See their [documentation](https://crate.io/docs/stable/sql/data_types.html#array). Examples for array of dynamic objects:

```
$table->arrayField('f_array','object as (age integer, name string');
```

### Basic usage

[](#basic-usage)

With crate DB connection, you can do simple and even more complex queries. Some examples are:

```
$articles = DB::select('select * from article where id = ?', array(1));

$user = DB::table('user')->where('email','some@example.com')->first();

$users = DB::table('user')->get();
```

### Eloquent

[](#eloquent)

To use Eloquent you'll need to use Crate Eloquent model.

```
use Julianmar\Crate\Eloquent\Model AS Eloquent;

class Article extends Eloquent {}
```

You can use (almost) all eloquent goodies as with the original eloquent model.

To use different table name, use:

```
protected $table = 'myArticles';
```

etc...

#### Eloquent model alias

[](#eloquent-model-alias)

Instead of adding

```
use Julianmar\Crate\Eloquent\Model AS Eloquent;
```

to all your eloquent classes, you can add an alias to `alias` array in `config/app.php`:

```
'CrateEloquent' => 'Julianmar\Crate\Eloquent\Model'
```

This will allow you to shorten the class definition to:

```
use CrateEloquent;
class Article extends CrateEloquent {}
```

#### Eloquent usage

[](#eloquent-usage)

It can be used mostly the same as an original Laravel eloquent model.

##### Getting all articles:

[](#getting-all-articles)

```
$articles = Article::all();
```

##### Getting by primary key:

[](#getting-by-primary-key)

```
$article = Article::find(1);
```

##### Using where(s):

[](#using-wheres)

```
$articles = Article::where('name','LIKE','Star%')->where('views','>',100)->get();
```

##### Using limits(s):

[](#using-limitss)

```
$articles = Article::where('name','LIKE','Star%')->take(10)->get();
```

##### Using whereIn:

[](#using-wherein)

```
$articles = Article::whereIn('id',[1,2,3])->get();
```

##### Using select for fields:

[](#using-select-for-fields)

```
$article = Article::select('id','name')->where('id',1)->first();
```

##### Using count:

[](#using-count)

```
$nb = Article::where('views','>',100)->count();
```

##### Complex where(s):

[](#complex-wheres)

```
$articles = Article::where('id','=',3)->orWhere(function($query)
            {
                $query->where('title', 'Star Wars 7')
                      ->orWhere('title', 'none');
            })->get();
```

*etc...*

##### Inserting

[](#inserting)

```
$new = Article::create([
    'id' => 1, // don't forget, there is no auto increment
    'title' => 'John Doe and friends',
    'summary' => '...',
    'array_of_strings' => ['one', 'two'],
    'object_field' => ['author' => 'Someone', 'title' => 'Editpr']
]);
```

##### Updating

[](#updating)

```
$article = Article::find(1);

$article->title = 'Brand new title';
$article->array_of_strings = ['tree', 'four'];
$article->object_field = ['author' => 'Someone Else', 'title' => 'Administrator'];
$article->save();
```

*Note*: when you update array or object field, whatever is in that field will be replaced with whatever you give. You cannot append or change just one value.

```
$article->object_field = ['crated_by' => 'Third Person'];
```

would *not* append 'created\_by' field to the fields that are already existing, but would overwrite and leave only 'created\_by' value in 'object\_field'. To fix this, do an update like:

```
$newValues = $article->object_field;
$newValues['created_by'] = 'Third Person';

$article->object_field = $newValues;
```

##### Deleting

[](#deleting)

```
$article = Article::find(1);
$article->delete();
```

### Changes

[](#changes)

#### Version 8.0

[](#version-80)

Updated project to work with laravel 5.8 No new functionalities, only fixes compatibility issues with changes in L 5.8.

Reworked test cases to work with phpunit 8 and 9.

#### Version 7.0

[](#version-70)

Updated project to work with laravel 5.7 No new functionalities, only fixes compatibility issues with changes in L 5.7.

#### Version 6.0

[](#version-60)

Updated project to work with laravel 5.6

#### Version 5.0

[](#version-50)

Updated project to work with laravel 5.5. The new `5.0` version works only with laravel 5.5.X.

#### Version 4.0

[](#version-40)

Updated and synced with laravel 5.4. The `runQueryCallback` method is different in 5.4 as it was in 5.3. So you'll have to use 4.0 with laravel 5.4.

This is an internal change, you work with laravel and crate as you did before. It's just a notice that 4.0 is not compatible with &lt;5.3 laravels.

#### Version 3.1

[](#version-31)

##### Exceptions

[](#exceptions)

Version 3.1. brings custom QueryException. This means that in case of SQL errors you'll be able to see SQL and it's parameters even if some of them are objects or arrays.

```
$foo = new stdClass();
$foo->bar = 'test';
User::create(['id'=>1,'name'=> $foo,'email'=>'user1@example.com']);

```

Throws:

```
QueryException:
SQLActionException [Validation failed for name: cannot cast {bar=test} to string] (SQL: insert into users (id, name, email) values (1, {"bar":"test"}, "user1@example.com"))

```

##### Connection

[](#connection)

Connection to crate can take table prefix. Add `prefix` key to your crate configuration to use it.

```
'crate' => array(
    'driver'   => 'crate',
    'host'     => 'localhost',
    'database' => 'doc',
    'port'     => 4200,
    'prefix'   => 'sys',
),
```

##### New types

[](#new-types)

- geoPoint
- geoShape
- ip

See [commit](https://github.com/Julianmar/laravel-crate.io/pull/10/commits/138289591e291aceb718e27a95123342be09b45b)and official crate [docs](https://crate.io/a/geo-shapes-in-crate/)

### Tests

[](#tests)

There are two kinds of tests:

- Lexical tests
- Data tests

### Lexical tests

[](#lexical-tests)

Lexical tests check if SQL statements produced by Query builder are semantically correct.

These tests are executed relatively fast. They check that all common SQLs are unaffected by code changes.

### Data tests

[](#data-tests)

Data tests connect to real Crate.io server and try to manage data there. Selecting, inserting, updating, deleting queries, all are tested.

These tests take longer to finish. We found that queriying for a record immediatelly after it has been inserted can produce negative results. Crate needs some time between insert (or delete, or update) requests and all next selects that query for this changes. So we have couple of `sleep(1)` statements in test code.

Running data tests for the first time will probably fail as `migration`table will not exist yet. Try rerunning test and it will proceed ok.

Conenction properties for tests are in `tests/DataTests/Config/database.php`file and can be changed for your setup.

Data tests will create:

- `t_migration` table for test table migrations,
- `t_users` table for some dummy user data.

###  Health Score

25

—

LowBetter than 37% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 72.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 ~0 days

Total

2

Last Release

2386d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/97816e4d4e6a40ecae06cbecad8d999c66eb7a058693ead8720172fbec4be98a?d=identicon)[JulianMar](/maintainers/JulianMar)

---

Top Contributors

[![RatkoR](https://avatars.githubusercontent.com/u/6648783?v=4)](https://github.com/RatkoR "RatkoR (45 commits)")[![JulianMar](https://avatars.githubusercontent.com/u/29117090?v=4)](https://github.com/JulianMar "JulianMar (10 commits)")[![dongilbert](https://avatars.githubusercontent.com/u/718028?v=4)](https://github.com/dongilbert "dongilbert (4 commits)")[![cweiske](https://avatars.githubusercontent.com/u/59036?v=4)](https://github.com/cweiske "cweiske (2 commits)")[![bergo](https://avatars.githubusercontent.com/u/619785?v=4)](https://github.com/bergo "bergo (1 commits)")

---

Tags

laravellaravel5cratecrate.iopdo\_crate

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/julianmar-laravel-crate/health.svg)

```
[![Health](https://phpackages.com/badges/julianmar-laravel-crate/health.svg)](https://phpackages.com/packages/julianmar-laravel-crate)
```

###  Alternatives

[essa/api-tool-kit

set of tools to build an api with laravel

52680.5k](/packages/essa-api-tool-kit)[ratkor/laravel-crate.io

Crate.io driver for Laravel

3617.2k](/packages/ratkor-laravel-crateio)[simplestats-io/laravel-client

Client for SimpleStats!

4515.5k](/packages/simplestats-io-laravel-client)[scottybo/laravel-google-my-business

A package for Laravel which implements the Google My Business API

3360.3k](/packages/scottybo-laravel-google-my-business)[casinelli/laravel-campaignmonitor

A Laravel 5 wrapper for Campaign Monitor

1444.7k](/packages/casinelli-laravel-campaignmonitor)[travoltron/plaid

Laravel specific wrapper for Plaid. Bankdata for developers.

274.8k](/packages/travoltron-plaid)

PHPackages © 2026

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