A comprehensive Laravel repository package that provides enterprise-level features for data access, performance optimization, analytics, and advanced querying capabilities. Perfect for applications handling large datasets, complex relationships, and requiring high-performance data operations.
- β Complete CRUD Operations - Standard create, read, update, delete operations
- β Clean Interface Separation - Well-defined contracts and implementations
- β Laravel Best Practices - Follows Laravel conventions and patterns
- οΏ½ Advanced Join Capabilities - Left, right, inner joins with relationship handling
- π Comprehensive Filtering - Dynamic field filtering with multiple operators
- π― Query String Parser - Parse complex URL filters with 20+ operators
- π Dynamic Scopes & Macros - Extensible query building with custom scopes
- π Large Dataset Optimization - Handle 5M+ records efficiently with cursor pagination
- β‘ Smart Pagination - Auto-optimization for different dataset sizes
- οΏ½ Performance Metrics - Built-in profiling and query analysis
- π§ Intelligent Caching - Advanced caching with tags and auto-invalidation
- οΏ½ Bulk Operations - Efficient bulk insert, update, delete, and upsert
- π Batch Processing - Process large datasets in manageable chunks
- π Data Export/Import - CSV, JSON, Excel export/import with streaming
- οΏ½ Relationship Manager - Advanced relationship handling and optimization
- π Repository Aggregations - Statistical analysis and trend calculations
- π Analytics Functions - Percentiles, correlations, moving averages
- οΏ½ Pivot Tables - Dynamic data pivoting and cross-tabulation
- π Histogram Generation - Data distribution analysis
- π Multi-Engine Search - Database, Elasticsearch, and Algolia integration
- π― Fuzzy Search - Similarity-based matching with configurable thresholds
- π Full-Text Search - Advanced text search with relevance scoring
- π§ Search Index Management - Automated indexing and reindexing
- πͺ Repository Events - Comprehensive event system for all operations
- οΏ½ Performance Monitoring - Real-time metrics and benchmarking
- π¨ Error Tracking - Built-in error handling and reporting
- π Audit Trail - Complete operation logging and tracking
- π‘οΈ Field Whitelisting - Secure field access control
- β Input Validation - Built-in data validation and sanitization
- οΏ½ Rate Limiting Ready - Prepared for rate limiting implementation
- π‘οΈ SQL Injection Protection - Secure query building
A Laravel package that implements the Repository pattern with a clean, intuitive API. This package provides a base repository class, interfaces, service provider bindings, CRUD operations, pagination support, and artisan commands to generate repositories.
- ποΈ Repository Pattern Implementation - Clean separation of data access logic
- π§ Base Repository Class - Common CRUD operations out of the box
- π― Repository Interface - Contract-based development
- π¦ Service Provider - Automatic Laravel integration
- π Advanced Querying - Search, filtering, and sorting capabilities
- οΏ½ Comprehensive Join Support - Inner, left, right, cross joins with subqueries
- π Aggregation Methods - Group by, having, raw expressions, and complex analytics
- οΏ½π Pagination Support - Built-in pagination methods
- β‘ Artisan Commands - Generate repositories with
make:repository - π§ͺ Fully Tested - Comprehensive test suite
- π Well Documented - Complete documentation and examples
- PHP 8.2 or higher
- Laravel 11.0 or 12.0
You can install the package via Composer:
composer require litepie/repositoryThe package will automatically register its service provider.
Use the artisan command to generate a repository:
php artisan make:repository UserRepositoryThis will create a repository class and interface in your app/Repositories directory.
<?php
namespace App\Http\Controllers;
use App\Repositories\Contracts\UserRepositoryInterface;
class UserController extends Controller
{
public function __construct(
private UserRepositoryInterface $userRepository
) {}
public function index()
{
$users = $this->userRepository->paginate(15);
return view('users.index', compact('users'));
}
public function store(Request $request)
{
$user = $this->userRepository->create($request->validated());
return redirect()->route('users.show', $user);
}
}// Create
$user = $userRepository->create(['name' => 'John Doe', 'email' => '[email protected]']);
// Read
$user = $userRepository->find(1);
$users = $userRepository->all();
// Update
$user = $userRepository->update(1, ['name' => 'Jane Doe']);
// Delete
$userRepository->delete(1);// Find with relationships
$user = $userRepository->with(['posts', 'comments'])->find(1);
// Search and filter
$users = $userRepository
->where('status', 'active')
->orderBy('created_at', 'desc')
->paginate(10);
// Custom queries
$users = $userRepository->findWhere([
['status', '=', 'active'],
['created_at', '>', now()->subDays(30)]
]);
// Advanced filtering
$users = $userRepository
->filter(['status' => 'active', 'role' => ['admin', 'moderator']])
->search('john', ['name', 'email'])
->dateRange('created_at', '2024-01-01', '2024-12-31')
->get();
// Request-based filtering
$users = $userRepository
->filterFromRequest(request()->all(), ['name', 'email', 'status'])
->sortFromRequest(request()->all(), ['name', 'created_at'])
->paginate(15);
// Join tables
$posts = $postRepository
->select(['posts.*', 'users.name as author_name'])
->join('users', 'posts.user_id', '=', 'users.id')
->where('posts.status', 'published')
->orderBy('posts.created_at', 'desc')
->get();
// Complex joins with conditions
$posts = $postRepository
->select(['posts.*', 'users.name as author_name'])
->selectRaw('COUNT(comments.id) as comments_count')
->join('users', 'posts.user_id', '=', 'users.id')
->leftJoin('comments', 'posts.id', '=', 'comments.post_id')
->where('posts.status', 'published')
->groupBy(['posts.id', 'users.name'])
->having('comments_count', '>', 5)
->orderByRaw('comments_count DESC')
->get();The base repository provides the following methods:
all($columns = ['*'])- Get all recordsfind($id, $columns = ['*'])- Find record by IDcreate(array $data)- Create new recordupdate($id, array $data)- Update existing recorddelete($id)- Delete record by ID
where($column, $operator = null, $value = null)- Add where clauseorWhere($column, $operator = null, $value = null)- Add or where clausewhereIn($column, array $values)- Add where in clausewhereBetween($column, array $values)- Add where between clausewhereNull($column)- Add where null clausewhereNotNull($column)- Add where not null clausewhereDate($column, $operator, $value)- Add where date clausewhereRaw($sql, array $bindings = [])- Add raw where clauseorderBy($column, $direction = 'asc')- Add order by clauseorderByRaw($sql, array $bindings = [])- Add raw order by clausewith($relations)- Eager load relationshipslimit($limit)- Limit resultsoffset($offset)- Offset results
join($table, $first, $operator = null, $second = null)- Add inner joinleftJoin($table, $first, $operator = null, $second = null)- Add left joinrightJoin($table, $first, $operator = null, $second = null)- Add right joininnerJoin($table, $first, $operator = null, $second = null)- Add inner joincrossJoin($table)- Add cross joinjoinWhere($table, callable $callback)- Add join with closure conditionsleftJoinWhere($table, callable $callback)- Add left join with closurejoinSub($query, $as, $first, $operator, $second)- Add subquery joinleftJoinSub($query, $as, $first, $operator, $second)- Add left subquery join
select($columns)- Select specific columnsselectRaw($expression, array $bindings = [])- Add raw select expressiondistinct()- Add distinct clausegroupBy($groups)- Add group by clausehaving($column, $operator, $value)- Add having clauseorHaving($column, $operator, $value)- Add or having clausehavingBetween($column, array $values)- Add having between clause
findWhere(array $where, $columns = ['*'])- Find records with conditionsfindWhereIn($column, array $values, $columns = ['*'])- Find records where column in valuespaginate($perPage = 15, $columns = ['*'])- Paginate resultssimplePaginate($perPage = 15, $columns = ['*'])- Simple pagination
count()- Count recordsexists($id)- Check if record existschunk($count, callable $callback)- Process records in chunks
<?php
namespace App\Repositories;
use App\Models\User;
use App\Repositories\Contracts\UserRepositoryInterface;
use Litepie\Repository\BaseRepository;
class UserRepository extends BaseRepository implements UserRepositoryInterface
{
public function model(): string
{
return User::class;
}
public function findActiveUsers()
{
return $this->where('status', 'active')->get();
}
public function findByEmail(string $email)
{
return $this->where('email', $email)->first();
}
public function getRecentUsers(int $days = 30)
{
return $this->where('created_at', '>=', now()->subDays($days))
->orderBy('created_at', 'desc')
->get();
}
}The package automatically binds repository interfaces to their implementations. You can also manually bind repositories in your AppServiceProvider:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Repositories\UserRepository;
use App\Repositories\Contracts\UserRepositoryInterface;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind(UserRepositoryInterface::class, UserRepository::class);
}
}When dealing with datasets over 5 million records, traditional pagination becomes slow. This package provides several optimization strategies:
// Much faster than OFFSET pagination for large datasets
$users = $userRepository
->where('status', 'active')
->cursorPaginate(20);
// For APIs
return response()->json([
'data' => $users->items(),
'next_cursor' => $users->nextCursor()?->encode(),
'has_more' => $users->hasMorePages(),
]);// Skip expensive COUNT(*) queries
$users = $userRepository
->where('status', 'active')
->fastPaginate(20);// Automatically chooses the best pagination method based on dataset size
$users = $userRepository
->where('status', 'active')
->smartPaginate(20);// Process large datasets without memory issues
$userRepository->chunk(1000, function ($users) {
foreach ($users as $user) {
// Process each user
}
});
// Or use lazy collections
$users = $userRepository->lazy(1000);
foreach ($users as $user) {
// Memory-efficient iteration
}| Method | 1M Records | 5M Records | 10M Records | Best For |
|---|---|---|---|---|
| Standard | ~500ms | ~2000ms | ~5000ms+ | Small datasets |
| Fast | ~50ms | ~100ms | ~150ms | No total needed |
| Cursor | ~10ms | ~15ms | ~20ms | Large datasets |
| Seek | ~5ms | ~10ms | ~15ms | Real-time feeds |
π Read the complete optimization guide β
Parse complex filter expressions from URL query strings for advanced search and filtering capabilities.
// Parse filter string like:
// "category:IN(Apartment,Bungalow);price:BETWEEN(100000,500000);status:EQ(Published);bua:GT(1000)"
$properties = $propertyRepository
->parseQueryFilters($filterString, ['category', 'price', 'status', 'bua'])
->cursorPaginate(20);- Comparison:
EQ,NEQ,GT,GTE,LT,LTE - Arrays:
IN,NOT_IN - Ranges:
BETWEEN,NOT_BETWEEN - Strings:
LIKE,NOT_LIKE,STARTS_WITH,ENDS_WITH - Nulls:
IS_NULL,IS_NOT_NULL - Dates:
DATE_EQ,DATE_GT,DATE_BETWEEN,YEAR,MONTH - JSON:
JSON_CONTAINS,JSON_LENGTH
// URL: /api/properties?filters=category:IN(Apartment,Villa);price:BETWEEN(100000,500000);bedrooms:IN(2,3,4)
public function search(Request $request, PropertyRepository $repository)
{
$filterString = $request->get('filters');
// Security: Define allowed fields
$allowedFields = ['category', 'price', 'bedrooms', 'status', 'location'];
$properties = $repository
->parseQueryFilters($filterString, $allowedFields)
->with(['images', 'location'])
->optimizedPaginate(20);
return response()->json([
'data' => $properties->items(),
'filters' => $repository->getFilterSummary($filterString),
]);
}// JavaScript filter builder
const filters = new FilterBuilder()
.addFilter('category', 'IN', ['Apartment', 'Villa'])
.addFilter('price', 'BETWEEN', [100000, 500000])
.build();
// Output: "category:IN(Apartment,Villa);price:BETWEEN(100000,500000)"
fetch(`/api/properties?filters=${encodeURIComponent(filters)}`)
.then(response => response.json())
.then(data => console.log(data));π Complete Query String Parser Guide β
Generate a new repository class and interface:
# Generate repository with interface
php artisan make:repository UserRepository
# Generate repository only (without interface)
php artisan make:repository UserRepository --no-interface
# Specify model
php artisan make:repository UserRepository --model=User
# Generate in custom directory
php artisan make:repository Admin/UserRepositoryYou can publish the configuration file:
php artisan vendor:publish --provider="Litepie\Repository\RepositoryServiceProvider" --tag="config"This will create a config/repository.php file where you can customize:
- Default repository namespace
- Default interface namespace
- Repository stub files
Run the tests with:
composer testYour repository package now includes these enterprise-level features:
// Statistical analysis
$stats = $repository->statisticalSummary('revenue');
$trends = $repository->trend('created_at', 'day', 'sales', 'sum');
$correlation = $repository->correlation('price', 'rating');
// Pivot tables
$salesData = $repository->pivot('category', 'month', 'revenue', 'sum');// Multi-engine search (Database, Elasticsearch, Algolia)
$results = $repository
->configureSearch(['engine' => 'elasticsearch'])
->search('laravel repository pattern');
// Fuzzy search with similarity matching
$fuzzyResults = $repository->fuzzySearch('jhon doe', 0.8);// Handle large datasets efficiently
$repository->bulkInsert($millionRecords, 2000);
$repository->bulkUpsert($data, ['email'], ['name', 'status']);
$repository->batchProcess($callback, 1000);// Advanced caching with tags and auto-invalidation
$data = $repository
->remember(3600)
->tags(['users', 'active'])
->where('status', 'active')
->get();// Built-in profiling and optimization
$repository->enableProfiling();
$data = $repository->complexQuery();
$report = $repository->getPerformanceReport();// Stream large exports
return $repository->streamExport('csv');
// Bulk import with conflict resolution
$imported = $repository->importFromCsv('data.csv', $mapping, [
'update_existing' => true,
'skip_errors' => true
]);// Listen to repository events
Event::listen('repository.User.created', function ($model) {
// Send notifications, update caches, etc.
});// Advanced relationship operations
$repository->syncRelation('tags', $postId, [1, 2, 3]);
$repository->createRelated('comments', $postId, $commentData);
$repository->loadMissingRelations($collection, ['user', 'tags']);For detailed documentation on all advanced features, see Advanced Features Guide.
- Advanced Features Guide - Complete guide to all enterprise features
- Query String Parser - URL filter parsing documentation
- Performance Optimization - Optimization strategies for large datasets
- API Reference - Complete API documentation
Perfect for applications like:
- E-commerce platforms - Product catalogs, order processing, inventory management
- Real estate systems - Property listings, advanced filtering, market analytics
- CRM systems - Customer data, relationship tracking, performance analytics
- Content management - Article publishing, media handling, user engagement tracking
- Financial applications - Transaction processing, reporting, audit trails
- IoT platforms - Sensor data, time-series analysis, bulk data processing
Please see CONTRIBUTING.md for details.
If you discover any security-related issues, please email [email protected] instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.
Please see CHANGELOG.md for more information on what has changed recently.