PHPackages                             ceddyg/query-builder-repository - 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. ceddyg/query-builder-repository

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

ceddyg/query-builder-repository
===============================

Repository using query builder. To return a Collection of stdClass or a simple stdClass. It's faster and use less memory than Eloquent if you just want data from database.

1.30.0(5y ago)117567[3 issues](https://github.com/CeddyG/query-builder-repository/issues)2MITPHPPHP &gt;=5.4.0

Since Jan 16Pushed 5y ago2 watchersCompare

[ Source](https://github.com/CeddyG/query-builder-repository)[ Packagist](https://packagist.org/packages/ceddyg/query-builder-repository)[ RSS](/packages/ceddyg-query-builder-repository/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependencies (1)Versions (64)Used By (2)

Query Builder Repository
========================

[](#query-builder-repository)

Laravel Repository using Query Builder (Fluent) instead of Eloquent. It returns a Collection of StdClass or a simple StdClass. It can receive arrays to create or update a record in the database and also delete a record or multiple record.

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

[](#installation)

```
composer require ceddyg/query-builder-repository
```

Usage
-----

[](#usage)

### Create a repository

[](#create-a-repository)

Firstly you have to create a repository and define the table, primary key and fillable.

By default the table will take the snake case in the plural of the repository's name without "Repository" and primary key is "id" by default.

```
namespace App\Repositories;

use CeddyG\QueryBuilderRepository\QueryBuilderRepository;

class ProductRepository extends QueryBuilderRepository
{
    //By default $sTable = 'products'
    protected $sTable = 'product';

    //By default $sPrimaryKey = 'id'
    protected $sPrimaryKey = 'id_products';

    //The attributes that are mass assignable.
    protected $fillable = ['name','category'];
}
```

### Avaible methods

[](#avaible-methods)

- [all(array $aColumns)](#all)
- [find(int $id, array $aColumns)](#find)
- [findByField(string $sField, mixed $mValue, array $aColumns)](#findbyfield)
- [findWhere(array $aWhere, array $aColumns)](#findwhere)
- [findWhereIn(string $sField, array $aWhere, array $aColumns)](#findwherein)
- [findWhereNotIn(string $sField, array $aWhere, array $aColumns)](#findwherenotin)
- [first(array $aColumns)](#first)
- [last(array $aColumns)](#last)
- [paginate(int $iLimit, array $aColumns, string $sPageName, int $iPage)](#paginate)
- [create(array $aAttributes)](#create)
- [update(int $id, array $aAttributes)](#update)
- [updateOrCreate(array $aAttributes)](#updateorcreate)
- [delete(array|int $id)](#delete)

### Additional methods

[](#additional-methods)

- [getTable](#gettable)
- [getPrimaryKey](#getprimarykey)
- [getFillFromView](#getfillfromview)
- [orderBy](#orderby)
- [limit](#limit)
- [datatable](#datatable)

#### all

[](#all)

Get all record in the database.

```
$oRepository = new ProductRepository();

$oProducts = $oRepository->all(); //Collection
//or
$oProducts = $oRepository->all(['name']); //Collection

foreach ($oProducts as $oProduct)
{
    //$oProduct is a StdClass
    echo oProduct->name;
}
```

#### find

[](#find)

Find a record with his ID.

```
$oRepository = new ProductRepository();

$oProduct = $oRepository->find(1); //StdClass with all columns
//or
$oProduct = $oRepository->find(1, ['name']); //StdClass with specific columns

echo oProduct->name;
```

#### findByField

[](#findbyfield)

Find records with a given field.

```
$oRepository = new ProductRepository();

$oProducts = $oRepository->findByField('name', 'Matrix'); //Collection
//or
$oProducts = $oRepository->findByField('name', 'Matrix', ['name', 'category']); //Collection

foreach ($oProducts as $oProduct)
{
    //$oProduct is a StdClass
    echo oProduct->name;
    echo oProduct->category;
}
```

#### findWhere

[](#findwhere)

Find records with a given where clause.

```
$oRepository = new ProductRepository();

$oProducts = $oRepository->findWhere(['price' => 20]); //Will find all products where the price = 20 and return a Collection
//or
$oProducts = $oRepository->findWhere(['price', 'action( route("admin.admin.destroy", "dummyId") )->attribute("onsubmit", "return confirm(\'Are you sure to delete ?\')")->delete() !!}'
                        +'{!! BootForm::submit("Delete", "btn-danger")->addClass("btn-block btn-xs") !!}'
                        +'{!! BootForm::close() !!}';
                    render = render.replace("dummyId", data);

                    return render;
                }
            }
        ],
        //Don't sort edit and delete column
        aoColumnDefs: [
            {
                bSortable: false,
                aTargets: [ -1, -2 ]
            }
        ]
    });
} );
```

#### orderBy

[](#orderby)

Order by a given field and direction. By defalut, the direction is 'asc'.

```
$oRepository = new ProductRepository();

$oProducts = $oRepository->orderBy('name')->all();
//or
$oProducts = $oRepository->orderBy('name')->findWhere(['categorie_id', 1]);
//or
$oProduct = $oRepository->orderBy('id', 'desc')->find(1, ['name']); //Useless
```

#### limit

[](#limit)

Limit the query.

```
$oRepository = new ProductRepository();

$oProducts = $oRepository->limit(0, 10)->all(); //Will take the first 10 records
//or
$oProducts = $oRepository->limit(5, 5)->all(); //Will take the 5 records after the 5th record.
//or
$oProduct = $oRepository->limit(0, 10)->find(1, ['name']); //Useless
```

Timestamp
---------

[](#timestamp)

You can automatically set a timestamp to a record.

```
namespace App\Repositories;

use CeddyG\QueryBuilderRepository\QueryBuilderRepository;

class ProductRepository extends QueryBuilderRepository
{
    /**
     * Indicates if the query should be timestamped.
     *
     * @var bool
     */
    protected $bTimestamp = true;

    /**
     * The name of the "created at" column.
     *
     * @var string
     */
    const CREATED_AT = 'created_at';

    /**
     * The name of the "updated at" column.
     *
     * @var string
     */
    const UPDATED_AT = 'updated_at';
}
```

Date
----

[](#date)

You can specify the default date format from the database and the default date format to store in the database.

```
namespace App\Repositories;

use CeddyG\QueryBuilderRepository\QueryBuilderRepository;

class ProductRepository extends QueryBuilderRepository
{

    protected $aFillable = ['name', 'category', 'price', 'date_limit'];

    protected $aDates = ['date_limit'];

    //By default $sDateFormatToGet = 'Y-m-d'
    protected $sDateFormatToGet = 'd/m/Y';

    //By default $sDateFormatToStore = 'Y-m-d'
    protected $sDateFormatToStore = 'Y-m-d';
}
```

Then if you have 2017-05-24 in your database you will have :

```
$oRepository = new ProductRepository();

$oProduct = $oRepository->first(['date_limit']);
echo $oProduct->date_limit; // 24/05/2017

$oRepository->update(1, ['date_limit' => '25/05/2017']) // Will store 2017-05-25 in the database
```

Custom attribute
----------------

[](#custom-attribute)

You can get specific attribute.

```
namespace App\Repositories;

use CeddyG\QueryBuilderRepository\QueryBuilderRepository;

class ProductRepository extends QueryBuilderRepository
{

    protected $aFillable = ['name', 'category', 'price', 'date_limit'];

    /**
     * Will change a fill that came from the database
     *
     * @param Collection|StdClass $oItem
     */
    public function getPriceAttribute($oItem)
    {
        return oItem->price * 1.2;
    }

    /**
     * Will create a new attribute that not in database
     *
     * @param Collection|StdClass $oItem
     */
    public function getReferenceAttribute($oItem)
    {
        return oItem->name.' '.oItem->category;
    }
}
```

And you can use it simply.

```
$oRepository = new ProductRepository();

$oProduct = $oRepository->first(['name', 'category', 'price', 'reference']);
```

You can specify what column you need for your custom attribute in the class.

```
namespace App\Repositories;

use CeddyG\QueryBuilderRepository\QueryBuilderRepository;

class ProductRepository extends QueryBuilderRepository
{
    protected $aFillable = ['name', 'category', 'price', 'date_limit'];

    /**
     * List of the customs attributes.
     *
     * @var array
     */
    protected $aCustomAttribute = [
        'reference' => [
            'name',
            'category'
        ],
        'tag_name' => [
            'tag.name'
        ]
    ];

    /**
     * Will create a new attribute that not in database
     *
     * @param Collection|StdClass $oItem
     */
    public function getReferenceAttribute($oItem)
    {
        return oItem->name.' '.oItem->category;
    }

    /**
     * Will create a new attribute that not in database
     *
     * @param Collection|StdClass $oItem
     */
    public function getTagNameAttribute($oItem)
    {
        return oItem->tag[0]->name;
    }

    public function tag()
    {
        $sForeignKey = 'fk_product';
        $sOtherForeignKey = 'fk_tag';

        //If $sForeignKey is null, the method will set 'product_id' (.'_id')
        //If $sOtherForeignKey is null, the method will set tag_id (.'_id')
        $this->belongsToMany('App\Repositories\TagRepository', 'product_tag', $sForeignKey, $sOtherForeignKey);
    }
}
```

And then.

```
$oRepository = new ProductRepository();

$oProduct = $oRepository->first(['price', 'reference', 'tag_name']);
```

Relationship
------------

[](#relationship)

To configure relationship, it's like Eloquent, you have to define a belongsTo, belongsToMany or hasMany with other repositories.

```
belongsTo($sRepository, $sForeignKey = null)
belongsToMany($sRepository, $sPivotTable, $sForeignKey = null, $sOtherForeignKey = null)
hasMany($sRepository, $sForeignKey = null)
```

```
namespace App\Repositories;

use Ceddyg\QueryBuilderRepository\QueryBuilderRepository;

class ProductRepository extends QueryBuilderRepository
{
    //By default $sTable = 'product'
    protected $sTable = 'products';

    //By default $sPrimaryKey = 'id'
    protected $sPrimaryKey = 'id_products';

    //The attributes that are mass assignable.
    protected $fillable = ['name','category'];

    public function tag()
    {
        $sForeignKey = 'fk_tag';

        //If $sForeignKey is null, the method will set tag_id (.'_id')
        $this->belongsTo('App\Repositories\TagRepository', $sForeignKey);
    }

    //or
    public function tag()
    {
        $sForeignKey = 'fk_product';
        $sOtherForeignKey = 'fk_tag';

        //If $sForeignKey is null, the method will set 'product_id' (.'_id')
        //If $sOtherForeignKey is null, the method will set tag_id (.'_id')
        $this->belongsToMany('App\Repositories\TagRepository', 'product_tag', $sForeignKey, $sOtherForeignKey);
    }

    //or
    public function tag()
    {
        $sForeignKey = 'fk_product';

        //If $sForeignKey is null, the method will set 'product_id' (.'_id')
        $this->hasMany('App\Repositories\TagRepository', 'product_id');
    }
}
```

Relations are considered like columns, so to add it :

```
$oRepository = new ProductRepository();

//It will take the name attribut and add the relation tag to an attribut "tag"
$oProduct = $oRepository->find(1, ['name', 'tag']);

echo $oProduct->name;
echo $oProduct->tag->name;

//If belongsToMany or hasMany relation, $oProduct->tag is a Collection
foreach ($oProduct->tag as $oTag)
{
    //$oTag is a StdClass
    echo $oTag->name;
}
```

To use it with [getFillFromView](#getfillfromview) you have to define what relations you allow :

```
/**
* List of relations we allow in getFillFromView.
*
* @var array
*/
protected $aRelations = ['tag'];
```

You can specify if the relations are returned as array or collection.

```
$oRepository = new ProductRepository();

//True : collection | false : array (good way to work with a lot of data)
$oRepository->setReturnCollection(false); //True by default

//It will take the name attribut and add the relation tag to an attribut "tag"
$oProduct = $oRepository->find(1, ['name', 'tag']);

foreach ($oProduct->tag as $oTag)
{
    //$oTag is a StdClass
    echo $oTag->name;
}
```

Connection
----------

[](#connection)

You can specify a database (set in config/database.php).

```
namespace App\Repositories;

use Ceddyg\QueryBuilderRepository\QueryBuilderRepository;

class ProductRepository extends QueryBuilderRepository
{
    protected $sConnection = 'mysql';
}
```

Or

```
$oRepository = new ProductRepository();
$oRepository->setConnection('mysql');

$oProduct = $oRepository->find(1);
```

ToDo List
---------

[](#todo-list)

- Add specific setter
- Select only the fillable's relation in the getFillFromView method (if we have $oItem-&gt;tag-&gt;tag\_name in the view, the system have to select tag\_name only)
- Add through relation
- Mix paginate and avaible methods
- Add a command to generate repository

###  Health Score

35

—

LowBetter than 79% of packages

Maintenance15

Infrequent updates — may be unmaintained

Popularity23

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity72

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~25 days

Recently: every ~88 days

Total

63

Last Release

1844d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b740b22a5f0d3efaabcf2fd4e8b399f5248eb7a583f1cc761539d84bab244e6a?d=identicon)[CeddyG](/maintainers/CeddyG)

---

Top Contributors

[![CeddyG](https://avatars.githubusercontent.com/u/16399426?v=4)](https://github.com/CeddyG "CeddyG (77 commits)")

---

Tags

laravelfluentquery builderrepository

### Embed Badge

![Health badge](/badges/ceddyg-query-builder-repository/health.svg)

```
[![Health](https://phpackages.com/badges/ceddyg-query-builder-repository/health.svg)](https://phpackages.com/packages/ceddyg-query-builder-repository)
```

###  Alternatives

[illuminatech/config

Provides support for Laravel application runtime configuration managed in persistent storage

14921.0k1](/packages/illuminatech-config)[ozankurt/repoist

Laravel ^5.6 repository generator.

9244.1k](/packages/ozankurt-repoist)[matchory/elasticsearch

The missing elasticsearch ORM for Laravel!

3059.0k](/packages/matchory-elasticsearch)

PHPackages © 2026

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