PHPackages                             mrtolouei/laravel-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. mrtolouei/laravel-repository

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

mrtolouei/laravel-repository
============================

A clean and flexible base repository package for Laravel that simplifies data access, enforces the repository pattern, and keeps your code organized and testable.

v1.1.0(1mo ago)09MITPHPPHP &gt;=8.0CI passing

Since May 5Pushed 1mo agoCompare

[ Source](https://github.com/mrtolouei/laravel-repository)[ Packagist](https://packagist.org/packages/mrtolouei/laravel-repository)[ RSS](/packages/mrtolouei-laravel-repository/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (2)Dependencies (6)Versions (3)Used By (0)

Laravel Repository
==================

[](#laravel-repository)

A clean and flexible base repository package for Laravel that simplifies data access, enforces the Repository Pattern, and keeps your application code organized, testable, and maintainable.

This package provides a reusable BaseRepository implementation with common Eloquent operations and a powerful filtering system.

[![License](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](LICENSE)[![Tests](https://github.com/mrtolouei/laravel-repository/actions/workflows/tests.yml/badge.svg)](https://github.com/mrtolouei/laravel-repository/actions/workflows/tests.yml)[![Latest Stable Version](https://camo.githubusercontent.com/8a4863cf5a91116ddea67041d571411b8d8ed670664d3e2c68b85b1e08edfc64/68747470733a2f2f706f7365722e707567782e6f72672f6d72746f6c6f7565692f6c61726176656c2d7265706f7369746f72792f762f737461626c65)](https://packagist.org/packages/mrtolouei/laravel-repository)

---

Table of Contents
-----------------

[](#table-of-contents)

1. [Features](#features)
2. [Requirements](#requirements)
3. [Installation](#installation)
4. [Basic Usage](#basic-usage)
5. [Available Methods](#available-methods)
6. [Filtering System](#filtering-system)
7. [Query Builder &amp; Chainable Methods](#query-builder--chainable-methods)
8. [Persisting Queries](#persisting-queries)
9. [CRUD Operations](#crud-operations)
10. [Advanced Usage](#advanced-usage)
11. [Testing](#testing)
12. [Contributing](#contributing)
13. [License](#license)

---

Features
--------

[](#features)

- Clean BaseRepository implementation
- Built‑in query builder helpers
- Dynamic filtering system with multiple operators
- Support for nested and OR conditions
- Relation filtering using dot notation
- Fluent query chaining
- Works with Laravel 9+
- Fully testable and extendable

---

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

[](#requirements)

- PHP &gt;= 8.0
- Laravel / Illuminate components &gt;= 9.0

---

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

[](#installation)

```
  composer require mrtolouei/laravel-repository
```

No configuration or service provider registration is required.

---

Basic Usage
-----------

[](#basic-usage)

Create a repository for your model by extending the `BaseRepository`.

### Example Model

[](#example-model)

```
App\Models\User
```

### Create Repository

[](#create-repository)

```
namespace App\Repositories;

use App\Models\User;use MrTolouei\Repository\Repositories\BaseRepository;

class UserRepository extends BaseRepository
{
    public function __construct(User $model)
    {
        parent::__construct($model);
    }

    protected array $allowedFilters = [
        'email',
        'name',
        'age',
        'created_at',
    ];
}
```

---

Available Methods
-----------------

[](#available-methods)

The `BaseRepository` provides many commonly used data access methods.

### Create

[](#create)

```
$user = $repository->create([
    'email' => 'john@example.com',
    'name' => 'John'
]);
```

### Find

[](#find)

```
$user = $repository->find($id);

$user = $repository->findOrFail($id);
```

### Update

[](#update)

```
$repository->update($id, [
    'name' => 'Updated Name'
]);
```

### Delete

[](#delete)

```
$repository->delete($id);
```

### Restore (Soft Deletes)

[](#restore-soft-deletes)

```
$repository->restore($id);
```

### Insert Multiple

[](#insert-multiple)

```
$repository->insert([
    ['email' => 'a@example.com'],
    ['email' => 'b@example.com']
]);
```

### Where

[](#where)

```
$repository->where('age', '>', 18)->all();
```

### OR Where

[](#or-where)

```
$repository
    ->where('age', 18)
    ->orWhere('age', 25)
    ->all();
```

### Where In

[](#where-in)

```
$repository->whereIn('id', [1,2,3])->all();
```

### Where Not In

[](#where-not-in)

```
$repository->whereNotIn('id', [4,5])->all();
```

### Order

[](#order)

```
$repository->orderBy('created_at', 'desc')->all();
```

### Limit

[](#limit)

```
$repository->limit(10)->all();
```

### Pagination

[](#pagination)

```
$repository->paginate(15);
```

### Aggregate Functions

[](#aggregate-functions)

```
$repository->count();

$repository->sum('amount');

$repository->avg('rating');
```

### Existence Check

[](#existence-check)

```
$repository->where('email', 'john@example.com')->exists();
```

---

Filtering System
----------------

[](#filtering-system)

The package includes a powerful **filtering trait** that allows structured filtering from arrays (useful for APIs).

Only fields listed in `$allowedFilters` can be filtered.

### Example

[](#example)

```
$repository->filter([
    'age' => ['gte' => 18],
    'email' => ['like' => 'gmail']
])->all();
```

### Supported Operators

[](#supported-operators)

KeywordSQL Equivalenteq=neq!=gt&gt;gte&gt;=lt&lt;lte&lt;=likeLIKEinIN (...)### Using Filters

[](#using-filters)

Example usage in a controller:

```
public function index(Request $request)
{
    $repo = new UserRepository(new User());

    $users = $repo
        ->filter($request->query())  // apply filters
        ->orderBy('created_at', 'desc')
        ->paginate(15);

    return response()->json($users);
}
```

Example filter input (from query parameters or request body):

```
{
  "email": {
    "like": "example.com"
  },
  "is_active": true,
  "or": [
    {
      "age": {
        "gte": 30
      }
    },
    {
      "roles.id": {
        "in": [
          1,
          2,
          3
        ]
      }
    }
  ]
}
```

### Explanation

[](#explanation)

- `email.like:` Finds users with email containing “example.com”
- `is_active:` Equals true
- `or` group: Matches users aged 30+ or belonging to roles with IDs 1, 2, 3

---

Query Builder &amp; Chainable Methods
-------------------------------------

[](#query-builder--chainable-methods)

All major query methods remain chainable:

MethodDescriptionExamplequery()Get Builder instance$userRepo-&gt;query()-&gt;where('active', true);where(...)Add where clause (supports array and closure)$repo-&gt;where(\['status' =&gt; 'active'\]);with(\[...\])Eager load relations$repo-&gt;with(\['posts', 'roles'\]);orderBy()Add order clause$repo-&gt;orderBy('created\_at', 'desc');limit()Limit results$repo-&gt;limit(10)-&gt;all();---

Persisting Queries
------------------

[](#persisting-queries)

Preserve query state across multiple operations:

```
$repo->persistQuery()
    ->where('is_active', true)
    ->orderBy('created_at', 'desc');

$firstActive = $repo->first();
$activeUsers = $repo->all();
```

Without calling `persistQuery()`, queries auto‑reset after each operation.

---

CRUD Operations
---------------

[](#crud-operations)

```
// Create
$newUser = $userRepo->create([
    'name' => 'Ali',
    'email' => 'ali@example.com',
]);

// Update
$updated = $userRepo->update($newUser->id, ['name' => 'Ali Tolouei']);

// Delete (soft)
$deletedCount = $userRepo->delete($newUser->id);

// Restore
$restoredCount = $userRepo->restore($newUser->id);

// Insert many
$userRepo->insert([
    ['name' => 'John', 'email' => 'john@example.com'],
    ['name' => 'Jane', 'email' => 'jane@example.com'],
]);

// First or create
$user = $userRepo->firstOrCreate(['email' => 'user@example.com'], ['name' => 'User']);

// Update or create
$user = $userRepo->updateOrCreate(['email' => 'user@example.com'], ['name' => 'Updated']);
```

---

Advanced Usage
--------------

[](#advanced-usage)

Powerful nested filter combinations with chaining:

```
$users = $userRepo
    ->filter([
        'is_active' => true,
        'roles.id' => ['in' => [1, 5]],
        'or' => [
            ['created_at' => ['gte' => '2024-01-01']],
            ['name' => ['like' => 'Ali']],
        ],
    ])
    ->with(['profile', 'posts'])
    ->orderBy('created_at', 'desc')
    ->paginate(10);
```

---

Testing
-------

[](#testing)

Run tests using PHPUnit:

```
  vendor/bin/phpunit
```

---

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

[](#contributing)

1. Fork the repository
2. Create a feature branch (`feature/awesome-feature`)
3. Commit your changes (`git commit -m 'Add new feature'`)
4. Push to the branch (`git push origin feature/awesome-feature`)
5. Open a Pull Request

---

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

###  Health Score

38

—

LowBetter than 83% of packages

Maintenance94

Actively maintained with recent releases

Popularity7

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity39

Early-stage or recently created project

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

Total

2

Last Release

31d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/70100016?v=4)[Alireza Tolouei](/maintainers/mrtolouei)[@mrtolouei](https://github.com/mrtolouei)

---

Top Contributors

[![mrtolouei](https://avatars.githubusercontent.com/u/70100016?v=4)](https://github.com/mrtolouei "mrtolouei (3 commits)")

---

Tags

filter-systemfilteringlaravellaravel-filteringlaravel-packagelaravel-repositoryrepository-pattern

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mrtolouei-laravel-repository/health.svg)

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

###  Alternatives

[yajra/laravel-oci8

Oracle DB driver for Laravel via OCI8

8733.1M23](/packages/yajra-laravel-oci8)[kirschbaum-development/eloquent-power-joins

The Laravel magic applied to joins.

1.6k29.9M42](/packages/kirschbaum-development-eloquent-power-joins)[psalm/plugin-laravel

Psalm plugin for Laravel

3325.1M337](/packages/psalm-plugin-laravel)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

45344.0k1](/packages/pressbooks-pressbooks)[glushkovds/phpclickhouse-laravel

Adapter of the most popular library https://github.com/smi2/phpClickHouse to Laravel

2051.4M2](/packages/glushkovds-phpclickhouse-laravel)[api-platform/laravel

API Platform support for Laravel

59156.3k10](/packages/api-platform-laravel)

PHPackages © 2026

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