PHPackages                             puncoz/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. [Framework](/categories/framework)
4. /
5. puncoz/laravel-repository

ActiveLibrary[Framework](/categories/framework)

puncoz/laravel-repository
=========================

A basic light weight package to implement Repository Design Pattern in Laravel.

v1.1.0(1y ago)3285↓36.4%1MITPHPPHP ^8.0CI failing

Since Feb 21Pushed 1y agoCompare

[ Source](https://github.com/puncoz-official/laravel-repository)[ Packagist](https://packagist.org/packages/puncoz/laravel-repository)[ Docs](https://github.com/JoBinsJP/laravel-repository)[ GitHub Sponsors](https://github.com/JoBinsJP)[ RSS](/packages/puncoz-laravel-repository/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (8)Versions (20)Used By (0)

Laravel Repository Pattern Implementation
=========================================

[](#laravel-repository-pattern-implementation)

[![Latest Version on Packagist](https://camo.githubusercontent.com/7c4a2bbfd3e22c4b53303f8c2dc57888f245e96aa4e70d81d512ff1b8f51d79a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f70756e636f7a2f6c61726176656c2d7265706f7369746f72792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/puncoz/laravel-repository)[![GitHub Tests Action Status](https://camo.githubusercontent.com/cd48eaceff295cc4539a068cf0fea6d0a85252e7a689cae7a20b807606733427/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f70756e636f7a2d6f6666696369616c2f6c61726176656c2d7265706f7369746f72792f72756e2d74657374732e796d6c3f6c6162656c3d7465737473266272616e63683d6d61696e)](https://github.com/puncoz-official/laravel-repository/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/a2e5555500b292948f293e5f3040e2e649f728637e6c9dcf5c936e5db0fa1d9c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f70756e636f7a2d6f6666696369616c2f6c61726176656c2d7265706f7369746f72792f7068702d63732d66697865722e796d6c3f6c6162656c3d636f64652532307374796c65266272616e63683d6d61696e)](https://github.com/puncoz-official/laravel-repository/actions?query=workflow%3A%22Check+%26+fix+styling%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/3484214038a6621dd4fb45e8c921cca2cfe0c1f6b2575672ad268d80d87b4794/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f70756e636f7a2f6c61726176656c2d7265706f7369746f72792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/puncoz/laravel-repository)

A lightweight and flexible implementation of the Repository Pattern for Laravel applications. This package provides a clean and consistent way to handle data access layers in your Laravel applications.

Features
--------

[](#features)

- Clean and simple Repository Pattern implementation
- Built-in filtering system with criteria pattern
- Data transformation using Fractal
- Scope query support
- Soft delete handling
- Eloquent model integration
- Flexible and extensible architecture

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

[](#installation)

You can install the package via composer:

```
composer require puncoz/laravel-repository
```

You can publish the config file with:

```
php artisan vendor:publish --provider="JoBins\LaravelRepository\LaravelRepositoryServiceProvider"
```

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

[](#basic-usage)

1. Create a repository interface:

```
use JoBins\LaravelRepository\Contracts\RepositoryInterface;

interface UserRepository extends RepositoryInterface
{
    // Add custom methods if needed
}
```

2. Create a repository implementation:

```
use JoBins\LaravelRepository\LaravelRepository;
use App\Models\User;

class UserEloquentRepository extends LaravelRepository implements UserRepository
{
    public function model(): string
    {
        return User::class;
    }
}
```

3. Register the repositories in the service provider:

```
use JoBins\LaravelRepository\LaravelRepositoryServiceProvider;

class RepositoryServiceProvider extends ServiceProvider
{
    public function register()
    {
        // ideally (for larger apps) recommended to maintain these bindings in config file (bindings/repositories.php)
        // bindings/repositories.php
        // return [
        //     UserRepository::class => UserEloquentRepository::class
        // ];

        collect(config('bindings.repositories'))->each(function (string $implementation, string $contract) {
            $this->app->bind($contract, $implementation);
        });
    }
}
```

In Laravel 11 and 12, manually register your service provider in bootstrap/providers.php:

```
return [
    // Other service providers...
    App\Providers\RepositoryServiceProvider::class,
];
```

4. Use the repository in your application:

```
class UserController extends Controller
{
    public function __construct(
        private UserRepository $repository
    ) {}

    public function index()
    {
        $users = $this->repository->all();

        return view('users.index', compact('users'));
    }
}
```

✅ Ready to rock!

Now, Laravel will automatically resolve the correct repository implementation via the interface wherever it's type-hinted using constructor injection or service container resolution.

⚙️ New Artisan Commands
-----------------------

[](#️-new-artisan-commands)

This package now includes three powerful Artisan commands to help scaffold Repositories, Transformers, and Filters with minimal effort.

🔧 Configuration You can customize the default paths via the repository file located at: config/repository.php

```
return [
    'repository_path'     => env('REPOSITORY_PATH', 'app/Repositories'),
    'interface_subfolder' => env('REPOSITORY_INTERFACE_SUBFOLDER', true),
    'repository_suffix'   => env('REPOSITORY_SUFFIX', 'EloquentRepository'),
    'interface_suffix'    => env('REPOSITORY_INTERFACE_SUFFIX', 'Repository'),
    'transformer_path'    => env('TRANSFORMER_PATH', 'app/Transformers'),
    'filter_path'         => env('FILTER_PATH', 'app/Filters'),
];
```

📦 make:repository

- interface\_subfolder:
- If true, the interface will be placed in an Interfaces/ subfolder.
- If false, it will be placed in the same folder as the repository.

Generate Repository and Interface as same time with:

```
php artisan make:repository {name}
```

Example

```
php artisan make:repository product/stock
```

This will generate:

- app/Repositories/Product/StockRepository.php
- app/Repositories/Product/Interfaces/StockRepositoryInterface.php (if interface\_subfolder is true)
- Or app/Repositories/Product/StockRepositoryInterface.php (if false)

It automatically handles:

- Folder creation
- Proper naming conventions
- Namespace and use statements

🔄 make:transformer

Generate a Transformer class.

```
php artisan make:transformer {name}
```

Example

```
php artisan make:transformer product/stock
```

✅ This will generate:

- app/Transformers/Product/StockTransformer.php

🔍 make:filter

Generate a Filter class for Eloquent query filtering.

```
php artisan make:filter {name}
```

Example

```
php artisan make:filter product/stock
```

✅ This will generate:

- app/Filters/Product/StockFilter.php

🧠 💡 Notes

- Slashes (/) in names are used to create subdirectories automatically.
- All files are created with proper namespaces and boilerplate code to get you started instantly.
- You can override default paths using the config file or environment variables.

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

[](#available-methods)

### Basic Operations

[](#basic-operations)

- `all(array $columns = ['*'])`: Get all records
- `find(int|string $modelId, array $columns = ['*'])`: Find by ID
- `findByField(string $field, mixed $value, array $columns = ['*'])`: Find by field
- `getByField(string $field, mixed $value, array $columns = ['*'])`: Get multiple (list/collection) by field
- `create(array $data)`: Create new record
- `update(array $data, int|string $modelId)`: Update record
- `delete(int|string $modelId)`: Delete record
- `deleteWhere(array $where)`: Delete by conditions
- `updateOrCreate(array $queries, array $values = [])`: Update or create record

### Filtering and Scopes

[](#filtering-and-scopes)

- `filter(FilterCriteria $filter)`: Apply filter criteria
- `skipFilters(bool $status = true)`: Skip filters
- `resetFilters()`: Reset all filters
- `scopeQuery(Closure $scopeQuery)`: Add query scope

### Data Transformation

[](#data-transformation)

- `setTransformer(TransformerAbstract|string $transformer)`: Set transformer
- `skipTransformer(bool $skip = true)`: Skip transformation
- `present(Collection|AbstractPaginator|Model $data)`: Present data using transformer

### Relations

[](#relations)

- `with(string|array $relations)`: Eager load relations
- `setIncludes(array|string $includes)`: Set transformer includes

Creating Custom Filters
-----------------------

[](#creating-custom-filters)

1. Create a filter class:

```
use Illuminate\Database\Eloquent\Builder;
use JoBins\LaravelRepository\Filters\Filterable;

class UserFilter extends Filterable
{
    /**
     * Hook that runs before any filter methods
     * [optional method]
     */
    public function preHook(Builder $query, array $filters): Builder
    {
        return $query;
    }

    /**
     * Filter method for 'search' query/filter parameter
     * Method name must be in camelCase with 'Filter' suffix
     * Second parameter will be the value from queries/filters array (coming in the constructor)
     */
    public function searchFilter(Builder $query, ?string $search): Builder
    {
        return $query->where(function (Builder $query) use ($search) {
            $query->orWhere('name', 'ilike', "%{$search}%")
                  ->orWhere('email', 'ilike', "%{$search}%");
        });
    }

    /**
     * Filter method for 'status' query/filter parameter
     */
    public function statusFilter(Builder $query, ?string $status): Builder
    {
        return $query->where('status', $status);
    }

    /**
     * Filter method for 'created_at' query/filter parameter
     * Example of how query/filter parameter names are converted to method names:
     * 'created_at' => 'createdAtFilter'
     */
    public function createdAtFilter(Builder $query, ?string $date): Builder
    {
        return $query->whereDate('created_at', $date);
    }

    /**
     * Hook that runs after all filter methods
     */
    public function postHook(Builder $query, array $filters): Builder
    {
        return $query;
    }
}
```

2. Apply the filter with queries:

```
// In your controller or service
$queries = [
    'search' => 'john',           // Will call searchFilter()
    'status' => 'active',         // Will call statusFilter()
    'created_at' => '2025-04-14', // Will call createdAtFilter()
];

// or,
$queries = $request->all();

$users = $repository
    ->filter(new UserFilter($queries))
    ->all();
```

### How Filters Work

[](#how-filters-work)

1. **Query Parameter to Method Mapping**:

    - queries/filters array is passed to the constructor
    - Query/filter parameters (keys in the array passed to the constructor) are automatically mapped to filter methods
    - Method names must be in camelCase and end with 'Filter' suffix
    - Examples:
        - `search` =&gt; `searchFilter()`
        - `user_status` =&gt; `userStatusFilter()`
        - `created_at` =&gt; `createdAtFilter()`
2. **Filter Method Signature**:

    ```
    public function someKeyFilter(Builder $query, mixed $value): Builder
    ```

    - First parameter: Eloquent Query builder instance
    - Second parameter: Value from the queries array
    - Must return: Eloquent Query Builder instance
3. **Filter Lifecycle**:

    ```
    preHook -> filterMethods -> postHook

    ```

    - `preHook`: Runs before any filter methods
    - Filter methods: Run in the order they are defined
    - `postHook`: Runs after all filter methods
4. **Optional Methods**:

    - All filter methods are optional
    - `preHook` and `postHook` are optional
    - Only methods matching query parameters will be called

Data Transformation
-------------------

[](#data-transformation-1)

The package uses [Fractal Transformers](https://fractal.thephpleague.com/transformers/) for data transformation. Here's how to implement transformers:

1. Create a transformer class:

```
use League\Fractal\TransformerAbstract;
use App\Models\User;

class UserTransformer extends TransformerAbstract
{
    protected array $availableIncludes = [
        'posts',
        'comments'
    ];

    public function transform(User $user): array
    {
        return [
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email,
            'created_at' => $user->created_at->toISOString(),
            'updated_at' => $user->updated_at->toISOString(),
        ];
    }

    public function includePosts(User $user)
    {
        return $this->collection($user->posts, new PostTransformer());
    }

    public function includeComments(User $user)
    {
        return $this->collection($user->comments, new CommentTransformer());
    }
}
```

2. Use transformation in your application:

```
// Get transformed data
$users = $repository->all(); // Returns non-transformed data (collection)

// Set transformer to the repository
// All subsequent queries (all, find, findByField, getByField etc.) will use this transformer and return transformed data
$users = $repository->setTransformer(UserTransformer::class)->all();

// Include relations in transformation
$users = $repository
    ->setTransformer(UserTransformer::class)
    ->setIncludes(['posts', 'comments'])
    ->all();

// Skip transformer for specific query
$rawUsers = $repository
    ->skipTransformer()
    ->all(); // Returns raw data
```

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

[](#contributing)

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

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Puncoz Nepal](https://github.com/puncoz)
- [All Contributors](../../contributors)

License
-------

[](#license)

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

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance47

Moderate activity, may be stable

Popularity19

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 61.8% 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 ~128 days

Recently: every ~283 days

Total

10

Last Release

390d ago

### Community

Maintainers

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

---

Top Contributors

[![puncoz](https://avatars.githubusercontent.com/u/7767424?v=4)](https://github.com/puncoz "puncoz (42 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (12 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (12 commits)")[![bedus-creation](https://avatars.githubusercontent.com/u/25701752?v=4)](https://github.com/bedus-creation "bedus-creation (2 commits)")

---

Tags

laravellaravel-repositoryjobins

###  Code Quality

Static AnalysisPHPStan

### Embed Badge

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

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

###  Alternatives

[laravel/passport

Laravel Passport provides OAuth2 server support to Laravel.

3.4k85.0M532](/packages/laravel-passport)[laravel/cashier

Laravel Cashier provides an expressive, fluent interface to Stripe's subscription billing services.

2.5k25.9M107](/packages/laravel-cashier)[laravel/scout

Laravel Scout provides a driver based solution to searching your Eloquent models.

1.7k49.4M479](/packages/laravel-scout)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k12.1M99](/packages/laravel-pulse)[laravel/pennant

A simple, lightweight library for managing feature flags.

57711.1M53](/packages/laravel-pennant)[laravel/cashier-paddle

Cashier Paddle provides an expressive, fluent interface to Paddle's subscription billing services.

264778.4k3](/packages/laravel-cashier-paddle)

PHPackages © 2026

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