PHPackages                             developermarshak/laravel-couchbase - 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. developermarshak/laravel-couchbase

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

developermarshak/laravel-couchbase
==================================

A Couchbase based Eloquent model and Query builder for Laravel

0.4.0(8y ago)11.7k1[1 issues](https://github.com/developermarshak/couchbase/issues)1MITPHPPHP ^7.0

Since Nov 9Pushed 8y ago1 watchersCompare

[ Source](https://github.com/developermarshak/couchbase)[ Packagist](https://packagist.org/packages/developermarshak/laravel-couchbase)[ Docs](https://github.com/ORT-Interactive-GmbH/laravel-couchbase)[ RSS](/packages/developermarshak-laravel-couchbase/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependencies (8)Versions (14)Used By (1)

Laravel Couchbase
=================

[](#laravel-couchbase)

[![Build Status](https://camo.githubusercontent.com/9b6fcd206ca7a5ca7db9cb8628bddacaec35c56ec284433dc5fa852d352fb845/687474703a2f2f696d672e736869656c64732e696f2f7472617669732f6d706f63696f742f6c61726176656c2d636f756368626173652e737667)](https://travis-ci.org/mpociot/laravel-couchbase)[![codecov](https://camo.githubusercontent.com/74c414f953ba404576ace19e3c6d85fdcac0d696f0fc9c36f2b0e05287310d4e/68747470733a2f2f636f6465636f762e696f2f67682f6d706f63696f742f6c61726176656c2d636f756368626173652f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/mpociot/laravel-couchbase)

An Eloquent model and Query builder with support for Couchbase, using the original Laravel API. *This library extends the original Laravel classes, so it uses exactly the same methods.*

Table of contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Configuration](#configuration)
- [Eloquent](#eloquent)
- [Optional: Alias](#optional-alias)
- [Query Builder](#query-builder)
- [Schema](#schema)
- [Extensions](#extensions)
- [Troubleshooting](#troubleshooting)
- [Examples](#examples)

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

[](#installation)

Make sure you have the Couchbase PHP driver installed. You can find installation instructions at

Installation using composer:

```
composer require developermarshak/laravel-couchbase

```

And add the service provider in `config/app.php`:

```
Mpociot\Couchbase\CouchbaseServiceProvider::class,
```

For usage with [Lumen](http://lumen.laravel.com), add the service provider in `bootstrap/app.php`. In this file, you will also need to enable Eloquent. You must however ensure that your call to `$app->withEloquent();` is **below** where you have registered the `CouchbaseServiceProvider `:

```
$app->register(Mpociot\Couchbase\CouchbaseServiceProvider::class);

$app->withEloquent();
```

The service provider will register a couchbase database extension with the original database manager. There is no need to register additional facades or objects. When using couchbase connections, Laravel will automatically provide you with the corresponding couchbase objects.

For usage outside Laravel, check out the [Capsule manager](https://github.com/illuminate/database/blob/master/README.md) and add:

```
$capsule->getDatabaseManager()->extend('couchbase', function($config)
{
    return new Mpociot\Couchbase\Connection($config);
});
```

Configuration
-------------

[](#configuration)

Change your default database connection name in `config/database.php`:

```
'default' => env('DB_CONNECTION', 'couchbase'),
```

And add a new couchbase connection:

```
'couchbase' => [
    'driver'   => 'couchbase',
    'host'     => env('DB_HOST', 'localhost'),
    'port'     => env('DB_PORT', 8091),
    'bucket'   => env('DB_DATABASE'),
    'username' => env('DB_USERNAME'),
    'n1ql_hosts' => [
        'http://'.env('DB_HOST', 'localhost').':8093'
    ]
],
```

You can connect to multiple servers or replica sets with the following configuration:

```
'couchbase' => [
    'driver'   => 'couchbase',
    'host'     => ['host1', 'host2'],
    'port'     => env('DB_PORT', 8091),
    'bucket'   => env('DB_DATABASE'),
    'username' => env('DB_USERNAME'),
    'n1ql_hosts' => [
        'http://host1:8093',
        'http://host2:8093'
    ]
],
```

Eloquent
--------

[](#eloquent)

This package includes a Couchbase enabled Eloquent class that you can use to define models for corresponding collections.

```
use Mpociot\Couchbase\Eloquent\Model as Eloquent;

class User extends Eloquent {}
```

As Couchbase does not provide the concept of tables, documents will instead be defined by a property called `_type`. Like the original Eloquent, the lower-casem plural name of the class will be used as the "table" name and will be placed inside the `_type` property of each document.

You may specify a custom type (alias for table) by defining a `table` property on your model:

```
use Mpociot\Couchbase\Eloquent\Model as Eloquent;

class User extends Eloquent {

    protected $table = 'my_users';

}
```

**NOTE:** Eloquent will also assume that each collection has a primary key column named `_id`. You may define a `primaryKey` property to override this convention. Likewise, you may define a `connection` property to override the name of the database connection that should be used when utilizing the model.

```
use Mpociot\Couchbase\Eloquent\Model as Eloquent;

class MyModel extends Eloquent {

    protected $connection = 'couchbase';

}
```

Everything else (should) work just like the original Eloquent model. Read more about the Eloquent on

### Optional: Alias

[](#optional-alias)

You may also register an alias for the Couchbase model by adding the following to the alias array in `config/app.php`:

```
'CouchbaseModel'       => 'Mpociot\Couchbase\Eloquent\Model',
```

This will allow you to use the registered alias like:

```
class MyModel extends CouchbaseModel {}
```

Query Builder
-------------

[](#query-builder)

The database driver plugs right into the original query builder. When using couchbase connections, you will be able to build fluent queries to perform database operations.

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

$user = DB::table('users')->where('name', 'John')->first();
```

If you did not change your default database connection, you will need to specify it when querying.

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

Read more about the query builder on

Schema
------

[](#schema)

As this Couchbase driver implementation uses a single bucket for all documents, a Schema builder is not implemented.

Examples
--------

[](#examples)

### Basic Usage

[](#basic-usage)

**Retrieving All Models**

```
$users = User::all();
```

**Retrieving A Record By Primary Key**

```
$user = User::find('517c43667db388101e00000f');
```

**Wheres**

```
$users = User::where('votes', '>', 100)->take(10)->get();
```

**Or Statements**

```
$users = User::where('votes', '>', 100)->orWhere('name', 'John')->get();
```

**And Statements**

```
$users = User::where('votes', '>', 100)->where('name', '=', 'John')->get();
```

**Using Where In With An Array**

```
$users = User::whereIn('age', [16, 18, 20])->get();
```

**Using Where Between**

```
$users = User::whereBetween('votes', [1, 100])->get();
```

**Where null**

```
$users = User::whereNull('updated_at')->get();
```

**Order By**

```
$users = User::orderBy('name', 'desc')->get();
```

**Offset &amp; Limit**

```
$users = User::skip(10)->take(5)->get();
```

**Distinct**

Distinct requires a field for which to return the distinct values.

```
$users = User::distinct()->get(['name']);
// or
$users = User::distinct('name')->get();
```

Distinct can be combined with **where**:

```
$users = User::where('active', true)->distinct('name')->get();
```

**Advanced Wheres**

```
$users = User::where('name', '=', 'John')->orWhere(function($query)
    {
        $query->where('votes', '>', 100)
              ->where('title', '!=', 'Admin');
    })
    ->get();
```

**Group By**

Selected columns that are not grouped will be aggregated with the $last function.

```
$users = Users::groupBy('title')->get(['title', 'name']);
```

**Aggregation**

```
$total = Order::count();
$price = Order::max('price');
$price = Order::min('price');
$price = Order::avg('price');
$total = Order::sum('price');
```

Aggregations can be combined with **where**:

```
$sold = Orders::where('sold', true)->sum('price');
```

**Like**

```
$user = Comment::where('body', 'like', '%spam%')->get();
```

**NOTE**: Like checks in Couchbase are case sensitive

**Incrementing or decrementing a value of a column**

Perform increments or decrements (default 1) on specified attributes:

```
User::where('name', 'John Doe')->increment('age');
User::where('name', 'Jaques')->decrement('weight', 50);
```

The number of updated objects is returned:

```
$count = User->increment('age');
```

You may also specify additional columns to update:

```
User::where('age', '29')->increment('age', 1, ['group' => 'thirty something']);
User::where('bmi', 30)->decrement('bmi', 1, ['category' => 'overweight']);
```

**Soft deleting**

When soft deleting a model, it is not actually removed from your database. Instead, a deleted\_at timestamp is set on the record. To enable soft deletes for a model, apply the SoftDeletingTrait to the model:

```
use Mpociot\Couchbase\Eloquent\SoftDeletes;

class User extends Eloquent {

    use SoftDeletes;

    protected $dates = ['deleted_at'];

}
```

For more information check

### Inserts, updates and deletes

[](#inserts-updates-and-deletes)

Inserting, updating and deleting records works just like the original Eloquent.

**Saving a new model**

```
$user = new User;
$user->name = 'John';
$user->save();
```

You may also use the create method to save a new model in a single line:

```
User::create(['name' => 'John']);
```

**Updating a model**

To update a model, you may retrieve it, change an attribute, and use the save method.

```
$user = User::first();
$user->email = 'john@foo.com';
$user->save();
```

**Deleting a model**

To delete a model, simply call the delete method on the instance:

```
$user = User::first();
$user->delete();
```

Or deleting a model by its key:

```
User::destroy('517c43667db388101e00000f');
```

For more information about model manipulation, check

### Relations

[](#relations)

Supported relations are:

- hasOne
- hasMany
- belongsTo
- belongsToMany
- embedsOne
- embedsMany

Example:

```
use Mpociot\Couchbase\Eloquent\Model as Eloquent;

class User extends Eloquent {

    public function items()
    {
        return $this->hasMany('Item');
    }

}
```

And the inverse relation:

```
use Mpociot\Couchbase\Eloquent\Model as Eloquent;

class Item extends Eloquent {

    public function user()
    {
        return $this->belongsTo('User');
    }

}
```

The belongsToMany relation will not use a pivot "table", but will push id's to a **related\_ids** attribute instead. This makes the second parameter for the belongsToMany method useless. If you want to define custom keys for your relation, set it to `null`:

```
use Mpociot\Couchbase\Eloquent\Model as Eloquent;

class User extends Eloquent {

    public function groups()
    {
        return $this->belongsToMany('Group', null, 'user_ids', 'group_ids');
    }

}
```

Other relations are not yet supported, but may be added in the future. Read more about these relations on

### EmbedsMany Relations

[](#embedsmany-relations)

If you want to embed models, rather than referencing them, you can use the `embedsMany` relation. This relation is similar to the `hasMany` relation, but embeds the models inside the parent object.

**REMEMBER**: these relations return Eloquent collections, they don't return query builder objects!

```
use Mpociot\Couchbase\Eloquent\Model as Eloquent;

class User extends Eloquent {

    public function books()
    {
        return $this->embedsMany('Book');
    }

}
```

You access the embedded models through the dynamic property:

```
$books = User::first()->books;
```

The inverse relation is auto*magically* available, you don't need to define this reverse relation.

```
$user = $book->user;
```

Inserting and updating embedded models works similar to the `hasMany` relation:

```
$book = new Book(['title' => 'A Game of Thrones']);

$user = User::first();

$book = $user->books()->save($book);
// or
$book = $user->books()->create(['title' => 'A Game of Thrones'])
```

You can update embedded models using their `save` method:

```
$book = $user->books()->first();

$book->title = 'A Game of Thrones';

$book->save();
```

You can remove an embedded model by using the `destroy` method on the relation, or the `delete` method on the model:

```
$book = $user->books()->first();

$book->delete();
// or
$user->books()->destroy($book);
```

If you want to add or remove an embedded model, without touching the database, you can use the `associate` and `dissociate` methods. To eventually write the changes to the database, save the parent object:

```
$user->books()->associate($book);

$user->save();
```

Like other relations, embedsMany assumes the local key of the relationship based on the model name. You can override the default local key by passing a second argument to the embedsMany method:

```
return $this->embedsMany('Book', 'local_key');
```

Embedded relations will return a Collection of embedded items instead of a query builder. Check out the available operations here:

### EmbedsOne Relations

[](#embedsone-relations)

The embedsOne relation is similar to the EmbedsMany relation, but only embeds a single model.

```
use Mpociot\Couchbase\Eloquent\Model as Eloquent;

class Book extends Eloquent {

    public function author()
    {
        return $this->embedsOne('Author');
    }

}
```

You access the embedded models through the dynamic property:

```
$author = Book::first()->author;
```

Inserting and updating embedded models works similar to the `hasOne` relation:

```
$author = new Author(['name' => 'John Doe']);

$book = Books::first();

$author = $book->author()->save($author);
// or
$author = $book->author()->create(['name' => 'John Doe']);
```

You can update the embedded model using the `save` method:

```
$author = $book->author;

$author->name = 'Jane Doe';
$author->save();
```

You can replace the embedded model with a new model like this:

```
$newAuthor = new Author(['name' => 'Jane Doe']);
$book->author()->save($newAuthor);
```

### MySQL Relations

[](#mysql-relations)

If you're using a hybrid Couchbase and SQL setup, you're in luck! The model will automatically return a Couchbase- or SQL-relation based on the type of the related model. Of course, if you want this functionality to work both ways, your SQL-models will need use the `Mpociot\Couchbase\Eloquent\HybridRelations` trait. Note that this functionality only works for hasOne, hasMany and belongsTo relations.

Example SQL-based User model:

```
use Mpociot\Couchbase\Eloquent\HybridRelations;

class User extends Eloquent {

    use HybridRelations;

    protected $connection = 'mysql';

    public function messages()
    {
        return $this->hasMany('Message');
    }

}
```

And the Couchbase-based Message model:

```
use Mpociot\Couchbase\Eloquent\Model as Eloquent;

class Message extends Eloquent {

    protected $connection = 'couchbase';

    public function user()
    {
        return $this->belongsTo('User');
    }

}
```

### Query Caching

[](#query-caching)

You may easily cache the results of a query using the remember method:

```
$users = User::remember(10)->get();
```

*From: *

### Query Logging

[](#query-logging)

By default, Laravel keeps a log in memory of all queries that have been run for the current request. However, in some cases, such as when inserting a large number of rows, this can cause the application to use excess memory. To disable the log, you may use the `disableQueryLog` method:

```
DB::connection()->disableQueryLog();
```

*From: *

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance0

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~3 days

Total

13

Last Release

3062d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/6b0a1ce2af5953f17b7befa77cc61e2656191a9a009af2afcdbc172b01906a69?d=identicon)[developermarshak](/maintainers/developermarshak)

---

Top Contributors

[![mpociot](https://avatars.githubusercontent.com/u/804684?v=4)](https://github.com/mpociot "mpociot (35 commits)")[![lquast](https://avatars.githubusercontent.com/u/10726291?v=4)](https://github.com/lquast "lquast (27 commits)")[![sonrac](https://avatars.githubusercontent.com/u/3766459?v=4)](https://github.com/sonrac "sonrac (11 commits)")[![alunapch](https://avatars.githubusercontent.com/u/24551725?v=4)](https://github.com/alunapch "alunapch (2 commits)")[![spresnac](https://avatars.githubusercontent.com/u/3299107?v=4)](https://github.com/spresnac "spresnac (2 commits)")[![crowcrow](https://avatars.githubusercontent.com/u/6330548?v=4)](https://github.com/crowcrow "crowcrow (1 commits)")[![Carbdrox](https://avatars.githubusercontent.com/u/15110985?v=4)](https://github.com/Carbdrox "Carbdrox (1 commits)")

---

Tags

laraveldatabasemodeleloquentcouchbase

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/developermarshak-laravel-couchbase/health.svg)

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

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[dyrynda/laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models.

4802.8M8](/packages/dyrynda-laravel-model-uuid)[pdphilip/elasticsearch

An Elasticsearch implementation of Laravel's Eloquent ORM

145360.2k4](/packages/pdphilip-elasticsearch)[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[toponepercent/baum

Baum is an implementation of the Nested Set pattern for Eloquent models.

3154.7k](/packages/toponepercent-baum)[friendsofcat/laravel-couchbase

A Couchbase based Eloquent model and Query builder for Laravel

1430.8k](/packages/friendsofcat-laravel-couchbase)

PHPackages © 2026

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