mrtolouei/laravel-repo-mate

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.0.0 2025-08-23 11:49 UTC

This package is auto-updated.

Last update: 2025-08-24 11:26:56 UTC


README

A modern, flexible, and filterable Eloquent repository base for Laravel.

Laravel RepoMate simplifies your data access layer by providing a reusable, testable, and maintainable repository structure. It includes filtering, chainable queries, pagination, CRUD operations, soft deletes, and batch inserts—all with Laravel Eloquent.

License Tests Latest Stable Version

Table of Contents

  1. Installation
  2. Creating a Repository
  3. Filterable Trait
  4. Using Filters
  5. Basic Query Methods
  6. Chainable Queries
  7. Custom Queries
  8. Persisting Queries
  9. CRUD Operations
  10. Advance Usages
  11. Testing
  12. Contributing
  13. License

Installation

Install via composer:

composer require mrtolouei/laravel-repo-mate

Creating a Repository

To create a new repository, extend BaseRepository and pass the model in the constructor:

use App\Models\User;
use RepoKit\Repositories\BaseRepository;

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

Filterable Trait

To create a new repository, extend BaseRepository and pass the model in the constructor:

Key properties:

  • $activeFilters: Parameters set at runtime.
  • $filterDefinitions: Define how filters are applied (column, type, operator, relation).
  • $filtersApplied: Internal flag to prevent applying filters multiple times.

Filter definition structure:

[
    'filter_name' => [
        'column'   => 'db_column',     // DB column name
        'type'     => 'string|integer|boolean|array|datetime', // Type of filter
        'operator' => '=',             // Optional, defaults to '='
        'relation' => 'relationName',  // Optional, for whereHas
    ]
]

Using Filters

Filters are defined in your repository as an array:

use App\Models\User;
use RepoKit\Repositories\BaseRepository;

class UserRepository extends BaseRepository
{
    protected array $filterDefinitions = [
        'email' => [
            'column' => 'email',
            'type'   => 'string'
        ],
        'roles' => [
            'column' => 'id',
            'type' => 'array',
            'operator' => '=',
            'resource' => 'roles' //Relation name in User model
        ],
        'age' => [
            'column' => 'age',
            'type' => 'integer',
            'operator' => '>='
        ],
        'is_active' => [
            'column' => 'is_active',
            'type' => 'boolean',
        ]          
    ];
}

You can apply filters dynamically at runtime using the repository’s setFilter() method. This is especially useful in a controller, where you can use query parameters from the HTTP request:

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

    // Apply filters from query parameters
    $users = $userRepo->setFilter($request->query())->all();

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

Explanation:

  • setFilter() accepts an array of filter parameters (e.g., from request()->query()).
  • The repository automatically applies the filters according to the filterDefinitions you defined in your repository.
  • This approach keeps your controller clean and leverages the repository’s built-in filtering system.

Basic Query Methods

Method Description Example
query(): Builder Get the query builder instance for customization $query = $userRepo->query();
where(...) Add a where clause $userRepo->where('is_active', true)->all();
with([...]) Eager load relations $userRepo->with(['posts', 'profile'])->all();
orderBy(...) Order results $userRepo->orderBy('created_at', 'desc')->all();
limit(int) Limit results $userRepo->limit(10)->all();

Chainable Queries

All query-building methods return $this for chaining:

$users = $userRepo
    ->where('is_active', true)
    ->orderBy('created_at', 'desc')
    ->limit(5)
    ->all();

Custom Queries

Get the underlying query builder for advanced queries:

$query = $userRepo->query();

$query->where('role_id', 2)
      ->orWhere('is_active', false)
      ->get();

Persisting Queries

Use persistQuery() to reuse the same query for multiple operations:

$query = $userRepo->persistQuery()
    ->where('role_id', 2)
    ->orderBy('created_at');

$firstUser = $query->first();
$allUsers = $query->all();

Without persistQuery(), queries are reset after each operation.

CRUD Operations

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

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

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

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

// Bulk insert
$userRepo->insert([
    ['name' => 'User1', 'email' => 'u1@example.com'],
    ['name' => 'User2', 'email' => 'u2@example.com'],
]);

Advanced Usage

$users = $userRepo
    ->setFilter(['role' => 2])
    ->where('is_active', true)
    ->orderBy('created_at', 'desc')
    ->with(['profile', 'posts'])
    ->paginate(10);
  • Combines filters, chainable queries, and pagination.
  • Supports eager loading relations.

Testing

composer test

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

This package is open-sourced software licensed under the MIT license.