PHPackages                             orkhanahmadov/eloquent-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. orkhanahmadov/eloquent-repository

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

orkhanahmadov/eloquent-repository
=================================

Eloquent Repository for Laravel

3.0.0(4y ago)2764.5k↓50%11[2 PRs](https://github.com/orkhanahmadov/eloquent-repository/pulls)MITPHPPHP ^8.0

Since Jul 28Pushed 2y ago3 watchersCompare

[ Source](https://github.com/orkhanahmadov/eloquent-repository)[ Packagist](https://packagist.org/packages/orkhanahmadov/eloquent-repository)[ Docs](https://github.com/orkhanahmadov/eloquent-repository)[ GitHub Sponsors](https://github.com/orkhanahmadov)[ RSS](/packages/orkhanahmadov-eloquent-repository/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (4)Dependencies (7)Versions (15)Used By (0)

Eloquent Repository for Laravel
===============================

[](#eloquent-repository-for-laravel)

[![Latest Stable Version](https://camo.githubusercontent.com/cf5bddc7cfbe031f3bd1d1c1aea828dadedc872028812a9af588c3f7bccd9a25/68747470733a2f2f706f7365722e707567782e6f72672f6f726b68616e61686d61646f762f656c6f7175656e742d7265706f7369746f72792f762f737461626c65)](https://packagist.org/packages/orkhanahmadov/eloquent-repository)[![Latest Unstable Version](https://camo.githubusercontent.com/b9525fc11e31425cae3d45cc6853df5ea005d3c4663194c9b37c991e1d5fd3da/68747470733a2f2f706f7365722e707567782e6f72672f6f726b68616e61686d61646f762f656c6f7175656e742d7265706f7369746f72792f762f756e737461626c65)](https://packagist.org/packages/orkhanahmadov/eloquent-repository)[![Total Downloads](https://camo.githubusercontent.com/9647a82711d2756f70f62c31477aa162440eae11a0525f472e8e24e40432da45/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6f726b68616e61686d61646f762f656c6f7175656e742d7265706f7369746f7279)](https://packagist.org/packages/orkhanahmadov/eloquent-repository)[![License](https://camo.githubusercontent.com/1c1deaf452bb4f1bf32deb83aa412b2a69c57537a25b815759e4a3a673bebff4/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6f726b68616e61686d61646f762f656c6f7175656e742d7265706f7369746f72792e737667)](https://github.com/orkhanahmadov/eloquent-repository/blob/master/LICENSE.md)

[![Build Status](https://camo.githubusercontent.com/c2504466d1d463d593a490f09662acee0109f476e59d4a5e204a932688c20df9/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f6f726b68616e61686d61646f762f656c6f7175656e742d7265706f7369746f72792e737667)](https://travis-ci.org/orkhanahmadov/eloquent-repository)[![Test Coverage](https://camo.githubusercontent.com/5a02340a99983327a282004658fdb2b09edde86ddb974185b2fc9cfc9393242d/68747470733a2f2f6170692e636f6465636c696d6174652e636f6d2f76312f6261646765732f33643566386566343130303466313238646638612f746573745f636f766572616765)](https://codeclimate.com/github/orkhanahmadov/eloquent-repository/test_coverage)[![Maintainability](https://camo.githubusercontent.com/49e2ffb173c6d3195fb5c8d2a2cbe4ea83366c8a187a73529c3a6463d27baa39/68747470733a2f2f6170692e636f6465636c696d6174652e636f6d2f76312f6261646765732f33643566386566343130303466313238646638612f6d61696e7461696e6162696c697479)](https://codeclimate.com/github/orkhanahmadov/eloquent-repository/maintainability)[![Quality Score](https://camo.githubusercontent.com/a2820168a87f43d0b0fa0f294f32318f964dfb61353f404a5d737a0f613712b6/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f6f726b68616e61686d61646f762f656c6f7175656e742d7265706f7369746f72792e737667)](https://scrutinizer-ci.com/g/orkhanahmadov/eloquent-repository)[![StyleCI](https://camo.githubusercontent.com/94616b13f17988236b78f087259ce5e771c784b0658e4d5043c3c604ec7328f2/68747470733a2f2f6769746875622e7374796c6563692e696f2f7265706f732f3139373332343330352f736869656c643f6272616e63683d6d6173746572)](https://github.styleci.io/repos/197324305)

Eloquent Repository package for Laravel created with total "repository pattern" in-mind.

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

[](#requirements)

Version requirement and compatibility with Laravel

**Version ^3.0** - Laravel **^9.0** or higher and **PHP 8.0** or higher.

**Version ^2.0** - Laravel **^6.0**, **^7.0** or **^8.0** or higher and **PHP 7.3** or higher.

**Version ^1.0** - Laravel **5.5**, **5.6**, **5.7**, **5.8** and **PHP 7.1** or higher.

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

[](#installation)

You can install the package via composer:

```
composer require orkhanahmadov/eloquent-repository
```

Usage
-----

[](#usage)

Create a repository class and extend `Orkhanahmadov\EloquentRepository\EloquentRepository` abstract class.

Repository class which extends `EloquentRepository` must implement `entity` method. When using Eloquent models it's enough to return model's full namespace from the method.

```
namespace App\Repositories;

use App\User;
use Orkhanahmadov\EloquentRepository\EloquentRepository;

class UserRepository extends EloquentRepository
{
    protected $entity = User::class;
}
```

Package also comes with console command that can create repository class. Pass repository class name to `make:repository` command to generate it.

```
php artisan make:repository UserRepository
```

This will create repository class inside `Repositories` folder in your app's autoload directory.

You can also pass Eloquent model namespace to `make:repository` command to automatically apply add that model to repository.

```
php artisan make:repository UserRepository --model=User
```

This will create `UserRepository` class and apply `User` model as entity to it.

You can use Laravel's container to inject `UserRepository` repository.

```
namespace App\Http\Controllers;

use App\Repositories\UserRepository;

class HomeController extends Controller
{
    public function index(UserRepository $userRepository)
    {
        return $userRepository->get();
    }
}
```

You can also skip creating dedicated repository class altogether, instead inject `Orkhanahmadov\EloquentRepository\EloquentRepository` and set Eloquent model entity dynamically.

```
namespace App\Http\Controllers;

use App\User;
use Orkhanahmadov\EloquentRepository\EloquentRepository;

class HomeController extends Controller
{
    public function index(EloquentRepository $repository)
    {
        return $repository->setEntity(User::class)->get();
    }
}
```

### Available methods

[](#available-methods)

Eloquent Repository class offers has many familiar shortcut methods from Eloquent.

**Create a model:**

```
$userRepository->create(['first_name' => 'John', 'last_name' => 'Doe']);
```

Creates a user with given parameters and returns created model instance.

**Return all models:**

```
$userRepository->all();
```

Finds and returns all users with all allowed columns.

**Return all models with listed columns:**

```
$userRepository->get(['id', 'first_name']);
```

Finds and returns all users with listed columns. You can skip list of columns, method will act same as `all()`.

**Paginate and return all models with given "per page" value:**

```
$userRepository->paginate(10);
```

Paginates all users with given "per page" value and returns paginated result.

**Find a user with primary key:**

```
$userRepository->find(1);
```

Finds user with given primary key and returns model instance. If model is not available `Illuminate\Database\Eloquent\ModelNotFoundException` exception will be thrown.

**Return all users with given "where" statement:**

```
$userRepository->getWhere('first_name', 'John');
```

Returns all users where `first_name` is "John".

You can also pass multiple multiple "where" statements in first parameter and skip second parameter.

```
$userRepository->getWhere(['first_name' => 'John', 'last_name' => 'Doe']);
```

Returns all users where `first_name` is "John" and `last_name` is "Doe".

**Return first user with given "where" statement:**

```
$userRepository->getWhereFirst('first_name', 'John');
```

Returns first user where `first_name` is "John".

You can also pass multiple multiple "where" statements in first parameter and skip second parameter.

```
$userRepository->getWhereFirst(['first_name' => 'John', 'last_name' => 'Doe']);
```

Returns first user where `first_name` is "John" and `last_name` is "Doe".

**Return all users with given "whereIn" statement:**

```
$userRepository->getWhereIn('first_name', ['John', 'Jane', 'Dave']);
```

Returns all users where `first_name` is "John", "Jane" or "Dave".

**Return first user with given "whereIn" statement:**

```
$userRepository->getWhereInFirst('first_name', ['John', 'Jane', 'Dave']);
```

Returns first user where `first_name` is "John", "Jane" or "Dave".

**Update a model with given properties:**

```
$user = $userRepository->find(1);
$userRepository->update($user, ['first_name' => 'Dave']);
$userRepository->findAndUpdate(1, ['first_name' => 'Dave']); // finds user with ID=1, updates it with given values and returns instance
```

Updates `$user` model's `first_name` to "Dave" and returns updated instance.

**Find a model using primary key and update with given properties:**

```
$userRepository->findAndUpdate(1, ['first_name' => 'Dave']);
```

Finds a user with given primary key, updates `first_name` to "Dave" and returns updated instance. If model is not available `Illuminate\Database\Eloquent\ModelNotFoundException` exception will be thrown.

**Delete a model:**

```
$user = $userRepository->find(1);
$userRepository->delete($user);
```

Deletes `$user` model.

**Find a model using primary key and delete:**

```
$userRepository->findAndDelete(1);
```

Finds a user with given primary key and deletes. If model is not available `Illuminate\Database\Eloquent\ModelNotFoundException` exception will be thrown.

**Find a "soft deleted" model:**

```
$userRepository->findFromTrashed(1);
```

Finds a "soft deleted" user with given primary key. If model is not using "soft delete" feature method will throw `BadMethodCallException` exception. If model is not available `Illuminate\Database\Eloquent\ModelNotFoundException` exception will be thrown.

**Restore a "soft deleted" model:**

```
$user = $userRepository->findFromTrashed(1);
$userRepository->restore($user);
```

Restores a "soft deleted" a `$user` model. If model is not using "soft delete" feature method will throw `BadMethodCallException` exception.

**Find a "soft deleted" model using primary key and restore:**

```
$userRepository->findAndRestore(1);
```

Finds a "soft deleted" user with given primary key and restores. If model is not using "soft delete" feature method will throw `BadMethodCallException` exception. If model is not available `Illuminate\Database\Eloquent\ModelNotFoundException` exception will be thrown.

### Criteria

[](#criteria)

Package uses "criteria" for creating flexible queries. To use criteria chain `withCriteria()` method to repository. List of available criteria:

**EagerLoad:**

Use `Orkhanahmadov\EloquentRepository\Repository\Eloquent\Criteria\EagerLoad` to eager load relationships with query.

```
$userRepository->withCriteria(new EagerLoad('posts', 'country'))->get();
```

This will return all users with `posts` and `country` relationships eager loaded.

**Scope:**

Use `Orkhanahmadov\EloquentRepository\Repository\Eloquent\Criteria\Scope` to apply eloquent query scopes.

```
$userRepository->withCriteria(new Scope('active', 'admin'))->get();
```

This will apply `active` and `active` scopes to query and return all available users.

**OrderBy:**

Use `Orkhanahmadov\EloquentRepository\Repository\Eloquent\Criteria\OrderBy` to order results with specified column and type.

```
$userRepository->withCriteria(new OrderBy('username', 'asc'))->get();
```

This will return order users by ascending `username` column and return all of them.

**Latest:**

Use `Orkhanahmadov\EloquentRepository\Repository\Eloquent\Criteria\Latest` to order results with specified column and in descending order.

```
$userRepository->withCriteria(new OrderBy('username'))->get();
```

This will return order users by descending `username` column and return all of them.

You can apply multiple scopes to repository at the same time.

```
$userRepository->withCriteria([
    new EagerLoad('posts', 'country'),
    new Scope('active', 'admin'),
    new OrderBy('id')
])->get();
```

You can create your own criteria classes and use them with `withCriteria()` method. Every criteria class must implement `Orkhanahmadov\EloquentRepository\Repository\Criteria\Criterion` interface. This interface requires having `apply($entity)` method:

```
use Orkhanahmadov\EloquentRepository\Repository\Criteria\Criterion;

class Ascending implements Criterion
{
    /**
     * @var string
     */
    private $column;

    /**
     * @param string $column
     */
    public function __construct($column = 'id')
    {
        $this->column = $column;
    }

    /**
     * @param $entity
     *
     * @return mixed
     */
    public function apply($entity)
    {
        return $entity->orderBy($this->column, 'asc');
    }
}
```

### Caching

[](#caching)

Repository also supports caching models. To enable caching implement `Orkhanahmadov\EloquentRepository\Repository\Contracts\Cacheable` interface to your repository:

```
namespace App\Repositories;

use App\User;
use Orkhanahmadov\EloquentRepository\Repository\Contracts\Cacheable;
use Orkhanahmadov\EloquentRepository\EloquentRepository;

class UserRepository extends EloquentRepository implements Cacheable
{
    protected $entity = User::class;
}
```

Once implemented, `all` and `find()` methods will cache results. Repository will empty the cache automatically when `update()`, `findAndUpdate()`, `delete()` and `findAndDelete()` methods used.

You can implement `cacheKey()` method in your repository to set cache key. Default is model's table name.

You can set cache time-to-live with `$cacheTTL` property. By default it is set to 3600 (1 hour). Alternatively you can implement `cacheTTL()` method in your repository to return cache time-to-live value. Repository will ignore `$cacheTTL` property value when `cacheTTL()` method is implemented.

You can implement `invalidateCache($model)` method in your repository to change cache invalidation logic when `update()`, `findAndUpdate()`, `delete()`, `findAndDelete()` methods being used.

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Orkhan Ahmadov](https://github.com/orkhanahmadov)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity40

Moderate usage in the ecosystem

Community14

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor1

Top contributor holds 99.2% 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 ~79 days

Recently: every ~178 days

Total

13

Last Release

1527d ago

Major Versions

1.2.1 → 2.0.02019-09-19

2.4.0 → 3.0.02022-03-14

PHP version history (4 changes)1.0.0PHP ^7.1

2.1.0PHP ^7.2

2.4.0PHP ^7.3|^8.0

3.0.0PHP ^8.0

### Community

Maintainers

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

---

Top Contributors

[![orkhanahmadov](https://avatars.githubusercontent.com/u/7041590?v=4)](https://github.com/orkhanahmadov "orkhanahmadov (132 commits)")[![absolutezeroo](https://avatars.githubusercontent.com/u/39636956?v=4)](https://github.com/absolutezeroo "absolutezeroo (1 commits)")

---

Tags

boilerplateclieloquentlaravelrepositorymodeleloquentrepositorylaravel-repositoryeloquent-repositoryeloquent-repository-generatorrepository-generator

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/orkhanahmadov-eloquent-repository/health.svg)

```
[![Health](https://phpackages.com/badges/orkhanahmadov-eloquent-repository/health.svg)](https://phpackages.com/packages/orkhanahmadov-eloquent-repository)
```

###  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)[prettus/l5-repository

Laravel 5|6|7|8|9|10|11|12 - Repositories to the database layer

4.2k10.8M145](/packages/prettus-l5-repository)[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[pdphilip/elasticsearch

An Elasticsearch implementation of Laravel's Eloquent ORM

145360.2k4](/packages/pdphilip-elasticsearch)[sleimanx2/plastic

Plastic is an Elasticsearch ODM and mapper for Laravel. It renders the developer experience more enjoyable while using Elasticsearch by providing a fluent syntax for mapping , querying and storing eloquent models.

508141.9k1](/packages/sleimanx2-plastic)

PHPackages © 2026

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