### Complete Caching Setup Example Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Caching.md Demonstrates a comprehensive setup for a repository, including cache duration, caching only read operations, selecting a cache store, and integrating with RequestCriteria. ```php namespace App\Repositories; use Prettus\Repository\Eloquent\BaseRepository; use Prettus\Repository\Contracts\CacheableInterface; use Prettus\Repository\Traits\CacheableRepository; use Prettus\Repository\Criteria\RequestCriteria; use App\Models\Post; class PostRepository extends BaseRepository implements CacheableInterface { use CacheableRepository; protected $fieldSearchable = [ 'title' => 'like', 'content' => 'like' ]; // Cache for 1 hour protected $cacheMinutes = 60; // Cache only read operations protected $cacheOnly = ['all', 'find', 'findByField', 'paginate']; public function model() { return Post::class; } public function boot() { // Use Redis for caching this repository $this->setCacheRepository(cache('redis')); // Enable RequestCriteria $this->pushCriteria(app(RequestCriteria::class)); } } // Usage $repository = app(PostRepository::class); // This gets cached $posts = $repository->all(); // Request bypasses cache $fresh = $repository->skipCache()->all(); // Or skip via query parameter // GET /api/posts?skipCache=1 // Cache automatically cleared on writes $repository->create(['title' => 'New Post']); $repository->update(['title' => 'Updated'], 1); $repository->delete(1); ``` -------------------------------- ### Repository Configuration Example Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/README.md Example configuration settings for pagination, caching, criteria parameters, and generator paths. ```php // config/repository.php 'pagination' => [ 'limit' => 15, // Default per-page ], 'cache' => [ 'enabled' => true, 'minutes' => 30, 'repository' => 'cache', // Cache store ], 'criteria' => [ 'params' => [ 'search' => 'search', 'orderBy' => 'orderBy', 'filter' => 'filter', 'with' => 'with', ], ], 'generator' => [ 'basePath' => app_path(), 'rootNamespace' => 'App\', ] ``` -------------------------------- ### Complete Example: Logging Post Activity Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Events.md A comprehensive example demonstrating how to log activities for Post creation, updates, and deletions using repository events. This listener should be registered in your EventServiceProvider. ```php namespace App\Listeners; use Prettus\Repository\Events\RepositoryEntityCreated; use Prettus\Repository\Events\RepositoryEntityUpdated; use Prettus\Repository\Events\RepositoryEntityDeleted; use App\Models\Post; use Spatie\Activitylog\Facades\Activity; class LogPostActivity { public function handleCreated(RepositoryEntityCreated $event) { if (!$event->getModel() instanceof Post) { return; } Activity::causedBy(auth()->user()) ->performedOn($event->getModel()) ->withProperties(['attributes' => $event->getModel()->toArray()]) ->log('Post created'); } public function handleUpdated(RepositoryEntityUpdated $event) { if (!$event->getModel() instanceof Post) { return; } Activity::causedBy(auth()->user()) ->performedOn($event->getModel()) ->withProperties(['dirty' => $event->getModel()->getDirty()]) ->log('Post updated'); } public function handleDeleted(RepositoryEntityDeleted $event) { if (!$event->getModel() instanceof Post) { return; } Activity::causedBy(auth()->user()) ->performedOn($event->getModel()) ->withProperties(['attributes' => $event->getModel()->toArray()]) ->log('Post deleted'); } } // Register in EventServiceProvider protected $listen = [ RepositoryEntityCreated::class => ['App\Listeners\LogPostActivity@handleCreated'], RepositoryEntityUpdated::class => ['App\Listeners\LogPostActivity@handleUpdated'], RepositoryEntityDeleted::class => ['App\Listeners\LogPostActivity@handleDeleted'], ]; ``` -------------------------------- ### Cache Configuration Example Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Caching.md Example configuration for caching in config/repository.php, showing global enable/disable, lifetime, repository selection, and auto-clear settings. ```php 'cache' => [ // Enable or disable caching globally 'enabled' => true, // Cache lifetime in minutes 'minutes' => 30, // Cache repository to use 'repository' => 'cache', // Auto-clear cache on write operations 'clean' => [ 'enabled' => true, 'on' => [ 'create' => true, 'update' => true, 'delete' => true, ] ], // Request parameter to skip cache 'params' => [ 'skipCache' => 'skipCache' ], // Whitelist/blacklist which methods to cache 'allowed' => [ 'only' => null, // Cache only these methods 'except' => null // Cache all except these methods ], ] ``` -------------------------------- ### Install l5-repository Package Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/README.md Install the l5-repository package using Composer. ```bash composer require prettus/l5-repository ``` -------------------------------- ### Complete PostRepository Example Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/BaseRepository.md A comprehensive example of a PostRepository extending BaseRepository. It demonstrates field searching, validation rules, model and presenter configuration, criteria pushing, and various usage patterns. ```php namespace App\Repositories; use Prettus\Repository\Eloquent\BaseRepository; use Prettus\Repository\Criteria\RequestCriteria; use Prettus\Validator\Contracts\ValidatorInterface; use App\Models\Post; use App\Validators\PostValidator; class PostRepository extends BaseRepository { protected $fieldSearchable = [ 'title' => 'like', 'content' => 'like', 'status' => '=', 'author.name' => 'like' ]; protected $rules = [ ValidatorInterface::RULE_CREATE => [ 'title' => 'required|string|max:255', 'content' => 'required|string' ], ValidatorInterface::RULE_UPDATE => [ 'title' => 'sometimes|string|max:255' ] ]; public function model() { return Post::class; } public function presenter() { return 'App\Presenters\PostPresenter'; } public function boot() { $this->pushCriteria(app(RequestCriteria::class)); } } // Usage $repository = app(PostRepository::class); // Get all with relations $posts = $repository->with('author')->all(); // Paginate with search $posts = $repository->paginate(15); // Advanced query $posts = $repository ->with('author', 'comments') ->orderBy('created_at', 'desc') ->findWhere([ 'status' => 'published', ['created_at', 'DATE >=', '2024-01-01'] ]); // Create with validation $post = $repository->create([ 'title' => 'New Post', 'content' => 'Content here', 'author_id' => 1 ]); // Update $updated = $repository->update(['status' => 'published'], $post->id); ``` -------------------------------- ### Example Post Presenter Implementation Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Presenters.md This example shows how to implement the PresenterInterface to transform a single post or a collection of posts. It maps posts to a specific array structure, converting the title to uppercase and generating a URL. ```php use Prettus\Repository\Contracts\PresenterInterface; class PostPresenter implements PresenterInterface { public function present($data) { if ($data instanceof Collection) { return $data->map(function($post) { return $this->transformPost($post); })->toArray(); } return $this->transformPost($data); } protected function transformPost($post) { return [ 'id' => $post->id, 'title' => strtoupper($post->title), 'url' => route('posts.show', $post->id) ]; } } ``` -------------------------------- ### Add Criteria Example Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/BaseRepository.md Shows how to add criteria instances or class names to the repository. ```php $repository->pushCriteria(new ActivePostsCriteria()); $repository->pushCriteria('App\Criteria\PaginatedCriteria'); ``` -------------------------------- ### README.md Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Provides an overview of the l5-repository package, including a quick start guide, feature summary, architecture overview, common patterns, and a troubleshooting guide. ```APIDOC ## README.md ### Description This file serves as the main entry point for understanding the l5-repository package. It covers the fundamental aspects of the library, from initial setup to its architectural design. ### Content Overview - Package Overview - Quick Start Guide - Feature Summary - Architecture Overview - Common Patterns - Troubleshooting Guide ``` -------------------------------- ### Repository Validation Example Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/README.md Illustrates how the repository automatically validates data against defined rules during creation. ```php $post = $repository->create([ 'title' => 'New Post', 'content' => 'Content...' ]); // Automatically validated against RULE_CREATE rules ``` -------------------------------- ### Magic Method Call Examples Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/BaseRepository.md Illustrates how unknown methods are delegated to the model, allowing fluent query building. ```php $repository->where('status', 'active')->get(); $repository->latest()->all(); ``` -------------------------------- ### Relation Count Example Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Criteria.md Demonstrates how relation counts are added as attributes to the models. ```PHP // ?withCount=comments // Post models will have ->comments_count attribute ``` -------------------------------- ### Common Query Methods Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/README.md Examples of common repository methods for retrieving data, including all, paginate, find, findByField, and findWhere. ```php // Get all $all = $repository->all(['id', 'title']); // Pagination $paginated = $repository->paginate(15); // Find by ID $post = $repository->find(1); // Find by field $posts = $repository->findByField('author_id', 1); // Find with conditions $posts = $repository->findWhere(['status' => 'published']); // Advanced conditions $posts = $repository->findWhere([ 'status' => 'published', ['created_at', 'DATE >=', '2024-01-01'], ['price', 'BETWEEN', [10, 100]] ]); ``` -------------------------------- ### configuration.md Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Offers a complete configuration reference, detailing all configuration options, examples for different environments, and how to manage custom namespaces and environment variables. ```APIDOC ## configuration.md ### Description This file details the configuration options available for the l5-repository package, enabling users to customize its behavior according to their project needs. ### Configuration Details - Complete Configuration Reference - All Config Options with Descriptions - Production and Development Examples - Custom Namespace Configuration - Environment Variables - Runtime Configuration Override ``` -------------------------------- ### Query Chaining Example Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/README.md Demonstrates how to chain multiple query builder methods to fetch posts with eager loading, ordering, and specific field exclusions. ```php $posts = $repository ->with(['author', 'comments']) ->orderBy('created_at', 'desc') ->hidden(['password']) ->skipPresenter() ->all(); ``` -------------------------------- ### Eager Load Relationship Example Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Criteria.md Shows how eager loading a relationship makes it available on the model. ```PHP // ?with=author // Post models will have ->author relationship loaded ``` -------------------------------- ### Controller Constructor with Repository Injection Source: https://github.com/andersao/l5-repository/blob/master/README.md Example of a controller constructor that injects the PostRepository. ```php namespace App\Http\Controllers; use App\PostRepository; class PostsController extends BaseController { /** * @var PostRepository */ protected $repository; public function __construct(PostRepository $repository){ $this->repository = $repository; } .... } ``` -------------------------------- ### Complete Post Validator Example Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Validators.md A comprehensive example of a `PostValidator` class defining rules for both creation and update operations, including custom messages and attributes. ```php namespace App\Validators; use Prettus\Validator\LaravelValidator; use Prettus\Validator\Contracts\ValidatorInterface; class PostValidator extends LaravelValidator { protected $rules = [ ValidatorInterface::RULE_CREATE => [ 'title' => 'required|string|max:255|unique:posts', 'content' => 'required|string|min:10', 'excerpt' => 'sometimes|string|max:500', 'author_id' => 'required|integer|exists:users,id', 'category_id' => 'required|integer|exists:categories,id', 'tags' => 'sometimes|array|exists:tags,id', 'featured_image' => 'sometimes|image|max:2048', 'published_at' => 'sometimes|date|after:today', 'status' => 'required|in:draft,published,archived' ], ValidatorInterface::RULE_UPDATE => [ 'title' => 'sometimes|string|max:255|unique:posts,title,:id', 'content' => 'sometimes|string|min:10', 'excerpt' => 'sometimes|string|max:500', 'author_id' => 'sometimes|integer|exists:users,id', 'category_id' => 'sometimes|integer|exists:categories,id', 'tags' => 'sometimes|array|exists:tags,id', 'featured_image' => 'sometimes|image|max:2048', 'published_at' => 'sometimes|date|after:today', 'status' => 'sometimes|in:draft,published,archived' ] ]; protected $customMessages = [ 'title.required' => 'Post title is required.', 'title.unique' => 'A post with this title already exists.', 'content.required' => 'Please provide post content.', 'content.min' => 'Content must be at least 10 characters.', 'author_id.exists' => 'Selected author does not exist.' ]; protected $customAttributes = [ 'author_id' => 'post author', 'category_id' => 'post category' ]; } namespace App\Repositories; use Prettus\Repository\Eloquent\BaseRepository; use App\Validators\PostValidator; use App\Models\Post; class PostRepository extends BaseRepository { protected $fieldSearchable = [ 'title' => 'like', 'content' => 'like' ]; public function model() { return Post::class; } public function validator() { return PostValidator::class; } } ``` -------------------------------- ### Applying a Single Criteria and Getting Results Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Criteria.md Demonstrates how to apply a specific criteria instance to the repository and immediately retrieve the filtered results. ```php $posts = $repository->getByCriteria(new PublishedCriteria()); ``` -------------------------------- ### PostRepository Implementation Example Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/BaseRepository.md Extend BaseRepository to create a repository for a specific Eloquent model. Define the model class and push default criteria in the boot method. ```php class PostRepository extends BaseRepository { protected $fieldSearchable = ['title', 'content']; public function model() { return 'App\Models\Post'; } public function boot() { $this->pushCriteria(app(RequestCriteria::class)); } } // Usage in controller $repository = app(PostRepository::class); ``` -------------------------------- ### Example Criteria Implementation Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Criteria.md This snippet shows how to implement the CriteriaInterface by defining the apply method to add a 'status' where clause to the query. ```php use Prettus\Repository\Contracts\CriteriaInterface; use Prettus\Repository\Contracts\RepositoryInterface; class PublishedCriteria implements CriteriaInterface { public function apply($model, RepositoryInterface $repository) { return $model->where('status', 'published'); } } ``` -------------------------------- ### Use Presenter with Repository and Model Source: https://github.com/andersao/l5-repository/blob/master/README.md Demonstrates fetching data transformed by a presenter, and how to skip the presenter to get the original model object. ```php $repository = app('App\PostRepository'); $repository->setPresenter("Prettus\Repository\Presenter\ModelFractalPresenter"); //Getting the result transformed by the presenter directly in the search $post = $repository->find(1); print_r( $post ); //It produces an output as array ... //Skip presenter and bringing the original result of the Model $post = $repository->skipPresenter()->find(1); print_r( $post ); //It produces an output as a Model object print_r( $post->presenter() ); //It produces an output as array ``` -------------------------------- ### Multiple Cache Stores Configuration Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/configuration.md Configures the package to use different cache stores, with an example of setting a specific cache store within a repository. ```php 'cache' => [ 'enabled' => true, 'minutes' => 30, 'repository' => 'cache', // Default store // In your repository: // public function boot() // { // $this->setCacheRepository(cache('redis')); // } ], ``` -------------------------------- ### Get First Record or Create It Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/BaseRepository.md Retrieves the first record matching the attributes, or creates it if no record is found. ```php public function firstOrCreate(array $attributes = []): mixed ``` -------------------------------- ### Async Event Handling for Post Creation Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Events.md Process repository events asynchronously by implementing the ShouldQueue interface. This example shows how to queue a post preview generation after a post is created. ```php namespace App\Listeners; use Illuminate\Contracts\Queue\ShouldQueue; use Prettus\Repository\Events\RepositoryEntityCreated; class ProcessPostCreation implements ShouldQueue { public function handle(RepositoryEntityCreated $event) { // This will be queued and processed asynchronously dispatch(new GeneratePostPreview($event->getModel())); } } ``` -------------------------------- ### Example: Invalid Presenter Class Configuration Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/errors.md Illustrates a RepositoryException caused by an invalid presenter class. The presenter must exist and implement the PresenterInterface. ```php class PostRepository extends BaseRepository { public function presenter() { return 'App\Presenters\NonExistentPresenter'; } } // Throws: RepositoryException if presenter doesn't implement PresenterInterface ``` ```php class PostRepository extends BaseRepository { public function presenter() { return 'App\Presenters\PostPresenter'; // Must exist and implement PresenterInterface } } ``` -------------------------------- ### Cache Key Generation Examples Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Caching.md Illustrates how cache keys are generated based on repository class, method, arguments, criteria, and request parameters to ensure unique keys for different queries. ```php // Different columns = different keys $key1 = $repository->getCacheKey('find', [1, ['id', 'title']]); $key2 = $repository->getCacheKey('find', [1, ['id', 'title', 'content']]); // Different criteria = different keys $repository->pushCriteria(new PublishedCriteria()); $key3 = $repository->getCacheKey('all'); $repository->popCriteria(PublishedCriteria::class); $key4 = $repository->getCacheKey('all'); // Different from key3 // Different request parameters = different keys $key5 = $repository->getCacheKey('paginate'); // for ?page=1 // Next request: ?page=2 $key6 = $repository->getCacheKey('paginate'); // Different from key5 ``` -------------------------------- ### Filter Columns Example Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Criteria.md Demonstrates how filtering columns affects the returned data structure. ```PHP // ?filter=id;title // Returns: [{"id": 1, "title": "Post Title"}, ...] ``` -------------------------------- ### Integration Test with Real Database Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/README.md Shows an example of integration testing for a repository by using the actual database and Laravel's testing utilities. ```php // Integration test with database class PostRepositoryTest extends TestCase { protected $repository; public function setUp(): void { parent::setUp(); $this->repository = app(PostRepository::class); } public function test_can_find_post() { $post = Post::factory()->create(); $found = $this->repository->find($post->id); $this->assertEquals($post->id, $found->id); } } ``` -------------------------------- ### Retrieving All Registered Criteria Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Criteria.md Illustrates how to get a collection of all criteria currently registered with the repository and iterate through them. ```php $criteria = $repository->getCriteria(); foreach ($criteria as $c) { echo get_class($c); } ``` -------------------------------- ### Create TestCase.php for Tests Source: https://github.com/andersao/l5-repository/blob/master/docs/superpowers/plans/2026-05-26-laravel-13-upgrade.md Create a `tests/TestCase.php` file that extends Orchestra's `TestCase`. This setup allows you to boot the `RepositoryServiceProvider` and test its functionality within a real Laravel application container. ```php firstOrCreate(['slug' => 'my-post']); ``` -------------------------------- ### Get Cache Repository Instance Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Caching.md Retrieves the current cache repository instance. Defaults to 'cache' configuration. ```php public function getCacheRepository(): CacheRepository ``` -------------------------------- ### Example: Invalid Criteria Implementation Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/errors.md Shows how a criteria class that does not implement CriteriaInterface will result in a RepositoryException. Ensure all criteria classes implement the required interface. ```php class SomeCriteria { // Missing: implements CriteriaInterface public function apply($model, $repository) { return $model->where('status', 'active'); } } $repository->pushCriteria(new SomeCriteria()); // Throws: RepositoryException // Message: "Class ... must be an instance of Prettus\Repository\Contracts\CriteriaInterface" ``` ```php use Prettus\Repository\Contracts\CriteriaInterface; use Prettus\Repository\Contracts\RepositoryInterface; class SomeCriteria implements CriteriaInterface { public function apply($model, RepositoryInterface $repository) { return $model->where('status', 'active'); } } ``` -------------------------------- ### Where Array Format Examples Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/types.md Illustrates various formats for constructing 'where' clauses, including simple equality, custom operators, and special operators like DATE, IN, BETWEEN, HAS, DOESNTHAVE, and EXISTS. ```php [ // Simple equality 'field' => 'value', // Custom operator ['field', 'operator', 'value'], // Special operators ['field', 'DATE', '2024-01-01'], ['field', 'DATE >=', '2024-01-01'], ['field', 'IN', ['value1', 'value2']], ['field', 'BETWEEN', [10, 100]], ['field', 'HAS', function($query) {}], ['field', 'DOESNTHAVE', function($query) {}], ['field', 'EXISTS', function($query) {}], ] ``` -------------------------------- ### Selecting Cache Repository per Repository Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Caching.md Configures a specific repository to use a different cache store (e.g., Redis) by overriding the default cache setup. This is done within the repository's boot method. ```php class PostRepository extends BaseRepository implements CacheableInterface { use CacheableRepository; protected $cacheMinutes = 60; public function boot() { // Use Redis cache for this repository $this->setCacheRepository(cache('redis')); } public function model() { return Post::class; } } ``` -------------------------------- ### LaravelValidator Configuration Example Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Validators.md Demonstrates how to configure the `$rules` property within a repository to automatically use Laravel's Validator with predefined rules for create and update operations. ```php class PostRepository extends BaseRepository { protected $rules = [ ValidatorInterface::RULE_CREATE => [ 'title' => 'required|string|max:255', 'content' => 'required|string' ], ValidatorInterface::RULE_UPDATE => [ 'title' => 'sometimes|string|max:255' ] ]; public function model() { return Post::class; } } ``` -------------------------------- ### Get First Record or New Instance Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/BaseRepository.md Retrieves the first record matching the attributes, or returns a new, unsaved instance if no record is found. ```php public function firstOrNew(array $attributes = []): mixed ``` -------------------------------- ### Customizing FractalPresenter with JsonApiSerializer Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Presenters.md This example shows how to extend FractalPresenter to use a different serializer, specifically the JsonApiSerializer. It also defines the transformer to be used for presentation. ```php class PostPresenter extends FractalPresenter { public function serializer() { return new \League\Fractal\Serializer\JsonApiSerializer(); } public function getTransformer() { return new PostTransformer(); } } ``` -------------------------------- ### RequestCriteria Field Search Configuration Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Criteria.md This example shows how to configure the $fieldSearchable property within a repository to define fields and their search operators for RequestCriteria. ```php protected $fieldSearchable = [ 'name' => 'like', 'email' => '=', 'age' => '>' ]; // Request: ?search=john&searchFields=name:like // Becomes: WHERE name LIKE '%john%' // Request: ?search=name:john;email:john@example.com // Becomes: WHERE name = 'john' OR email = 'john@example.com' ``` -------------------------------- ### Constructor Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/BaseRepository.md Initializes the repository, creates the model instance, sets up presenter and validator, then calls the `boot()` method for subclass initialization. ```APIDOC ## Constructor ### Description Initializes the repository, creates the model instance, sets up presenter and validator, then calls the `boot()` method for subclass initialization. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php public function __construct(Application $app) ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Get or New Instance with `firstOrNew` Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/RepositoryInterface.md Use `firstOrNew` to retrieve the first matching record or create a new, unsaved instance if no record is found. Attributes can be provided for the new instance. ```php public function firstOrNew(array $attributes = []): mixed ``` ```php $post = $repository->firstOrNew(['slug' => 'new-post']); ``` -------------------------------- ### boot Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/BaseRepository.md Called after initialization. Override to register default criteria and configure the repository. ```APIDOC ## boot ### Description Called after initialization. Override to register default criteria and configure the repository. ### Method Public ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php public function boot() ``` ### Response #### Success Response (200) None #### Response Example ```php public function boot() { $this->pushCriteria(app(RequestCriteria::class)); $this->pushCriteria(new ActivePostsCriteria()); } ``` ``` -------------------------------- ### Write RepositoryServiceProvider Boot Test Source: https://github.com/andersao/l5-repository/blob/master/docs/superpowers/plans/2026-05-26-laravel-13-upgrade.md Create `tests/RepositoryServiceProviderTest.php` to test the `RepositoryServiceProvider`. This test suite verifies that the configuration is merged correctly, the translation namespace is registered, and the publishable configuration path is set. ```php assertIsArray(config('repository')); $this->assertArrayHasKey('cache', config('repository')); } public function test_translation_namespace_is_registered(): void { $line = trans('repository::criteria.name'); $this->assertNotSame('repository::criteria.name', $line, 'translation namespace not loaded'); } public function test_publishable_config_path_is_registered(): void { $published = $this->app['config']->get('repository.cache.enabled'); $this->assertNotNull($published); } } ``` -------------------------------- ### Creating and Registering Dedicated Listener Classes Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Events.md Define dedicated listener classes for handling repository events. This promotes better code organization and reusability. The example shows a listener for entity creation. ```php namespace App\Listeners; use Prettus\Repository\Events\RepositoryEntityCreated; class LogRepositoryActivity { public function handle(RepositoryEntityCreated $event) { $model = $event->getModel(); $repository = $event->getRepository(); activity() ->causedBy(auth()->user()) ->performedOn($model) ->withProperties(['repository' => get_class($repository)]) ->log('created'); } } ``` ```php protected $listen = [ RepositoryEntityCreated::class => [ 'App\Listeners\LogRepositoryActivity', ], ]; ``` -------------------------------- ### Example Fractal Transformer Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Presenters.md This example defines a League Fractal transformer for a Post model. It specifies how each attribute of the Post model should be transformed into the output array, including type casting and date formatting. ```php use League\Fractal\TransformerAbstract; class PostTransformer extends TransformerAbstract { public function transform(Post $post) { return [ 'id' => (int) $post->id, 'title' => $post->title, 'content' => $post->content, 'author_id' => (int) $post->author_id, 'created_at' => $post->created_at->toIso8601String() ]; } } ``` -------------------------------- ### Search Data with Specific Field and Operator Source: https://github.com/andersao/l5-repository/blob/master/README.md Use the 'search' parameter with specific field and operator combinations, even without 'searchFields' for all parameters. This example uses '=' for the 'id' field. ```http http://prettus.local/users?search=id:2;age:17;email:john@gmail.com&searchFields='id':= ``` -------------------------------- ### getModel Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/BaseRepository.md Get the current Eloquent model instance. ```APIDOC ## getModel ### Description Get the current Eloquent model instance. ### Method Public ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php public function getModel(): Model ``` ### Response #### Success Response (200) - **Model** - The underlying Eloquent model #### Response Example ```php $model = $repository->getModel(); $table = $model->getTable(); ``` ``` -------------------------------- ### Run full test suite on default versions Source: https://github.com/andersao/l5-repository/blob/master/docs/superpowers/plans/2026-05-26-laravel-13-upgrade.md Update dependencies to their latest allowed versions and run the full test suite to ensure compatibility with current stable versions. ```bash composer update --with-all-dependencies vendor/bin/phpunit ``` -------------------------------- ### limit Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/BaseRepository.md Gets a limited number of results, internally calling the `take` method. ```APIDOC ## limit ### Description Get limited results (calls take internally). ### Method ```php public function limit($limit, $columns = ['*']): mixed ``` ``` -------------------------------- ### Unit Test with Mockery Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/README.md Illustrates how to perform unit testing on a repository using Mockery to mock dependencies and simulate method calls. ```php // Unit test with mock $mockRepository = Mockery::mock(PostRepository::class); $mockRepository->shouldReceive('find') ->with(1) ->andReturn(new Post(['id' => 1])); ``` -------------------------------- ### Minimal Configuration Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/configuration.md A basic configuration with pagination limit and cache disabled. ```php return [ 'pagination' => ['limit' => 15], 'cache' => ['enabled' => false], ]; ``` -------------------------------- ### Fluent Chaining and Direct Repository Methods Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/README.md Demonstrates using the repository for fluent chaining of query methods and direct calls for specific operations. ```php // Fluent chaining $posts = $repository ->with('author') ->orderBy('created_at', 'desc') ->paginate(); // Direct methods $post = $repository->find(1); $posts = $repository->all(['id', 'title']); ``` -------------------------------- ### limit Method Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/BaseRepository.md Gets a limited set of results, internally calling the take method. ```php public function limit($limit, $columns = ['*']): mixed ``` -------------------------------- ### Get Cache Lifetime Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Caching.md Retrieves the cache lifetime in minutes. Defaults to 30 minutes. ```php public function getCacheTime(): int ``` -------------------------------- ### Get Simply Paginated Records Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/BaseRepository.md Retrieves simply paginated records without a total count. ```php public function simplePaginate($limit = null, $columns = ['*']): mixed ``` -------------------------------- ### Generate Repository with Fillable Fields Source: https://github.com/andersao/l5-repository/blob/master/README.md Creates a repository and specifies which fields are fillable. ```terminal php artisan make:repository "Blog\Post" --fillable="title,content" ``` -------------------------------- ### Apply Custom Scope Query Source: https://github.com/andersao/l5-repository/blob/master/README.md Applies a custom scope to the repository query, for example, for ordering results. ```php $posts = $this->repository->scopeQuery(function($query){ return $query->orderBy('sort_order','asc'); })->all(); ``` -------------------------------- ### makeModel Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/BaseRepository.md Create and return a new model instance. ```APIDOC ## makeModel ### Description Create and return a new model instance. ### Method Public ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php public function makeModel(): Model ``` ### Response #### Success Response (200) - **Model** - New model instance #### Response Example ```php $repository->makeModel(); ``` ``` -------------------------------- ### Get Model Instance Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/BaseRepository.md Retrieve the current Eloquent model instance managed by the repository to access its properties or methods. ```php $model = $repository->getModel(); $table = $model->getTable(); ``` -------------------------------- ### Get Results by Specific Criteria Source: https://github.com/andersao/l5-repository/blob/master/README.md Retrieves results directly by applying a specific Criteria instance to the repository query. ```php $posts = $this->repository->getByCriteria(new MyCriteria()); ``` -------------------------------- ### Setting Default Criteria in Boot Method Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Criteria.md Applies default criteria automatically when a repository is booted, such as published status and request criteria. ```php public function boot() { $this->pushCriteria(new PublishedCriteria()); $this->pushCriteria(app(RequestCriteria::class)); } ``` -------------------------------- ### Custom Criteria Parameter Names Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Criteria.md Example of changing default parameter names for criteria, like using '?q' for search. ```PHP 'criteria' => [ 'params' => [ 'search' => 'q', // Use ?q instead of ?search 'orderBy' => 'sort_by', // Use ?sort_by instead of ?orderBy ] ], ``` -------------------------------- ### Make Presenter Instance Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/BaseRepository.md Create and register a presenter instance. If no presenter is provided, it uses the class name returned by the `presenter()` method. ```php public function makePresenter($presenter = null): PresenterInterface|null { // ... implementation details ... } ``` -------------------------------- ### Implement Presentable Interface in Model Source: https://github.com/andersao/l5-repository/blob/master/README.md Make your model implement `Presentable` and use `PresentableTrait` to enable presenting model data at any time. ```php namespace App; use Prettus\Repository\Contracts\Presentable; use Prettus\Repository\Traits\PresentableTrait; class Post extends Eloquent implements Presentable { use PresentableTrait; protected $fillable = [ 'title', 'author', ... ]; ... } ``` -------------------------------- ### Get Searchable Fields with `getFieldsSearchable` Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/RepositoryInterface.md Retrieve the list of fields that are configured as searchable for the repository. This is typically used with criteria-based searching. ```php public function getFieldsSearchable(): array ``` ```php $searchable = $repository->getFieldsSearchable(); // Returns: ['name', 'email', 'description'] ``` -------------------------------- ### Standard API Error Response Format Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/errors.md Example of a standard JSON structure for API error responses, particularly for validation failures. ```json { "message": "Validation failed", "errors": { "title": [ "Title is required" ], "email": [ "Email must be a valid email address", "Email has already been taken" ] } } ``` -------------------------------- ### Get Paginated Records Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/BaseRepository.md Retrieves paginated records. Supports 'paginate' or 'simplePaginate' methods. Uses a default limit if none is provided. ```php public function paginate($limit = null, $columns = ['*'], $method = "paginate"): mixed ``` -------------------------------- ### makePresenter Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/BaseRepository.md Create and register a presenter instance. ```APIDOC ## makePresenter ### Description Create and register a presenter instance. ### Method Public ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php public function makePresenter($presenter = null): PresenterInterface|null ``` ### Response #### Success Response (200) - **PresenterInterface|null** - Presenter instance or null #### Response Example ```php $repository->makePresenter(); ``` ``` -------------------------------- ### Complete Post Presenter Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Presenters.md Extends FractalPresenter to define a PostPresenter, specifying the PostTransformer and a JSON API serializer. Includes example API usage. ```php namespace App\Presenters; use Prettus\Repository\Presenter\FractalPresenter; use App\Transformers\PostTransformer; class PostPresenter extends FractalPresenter { public function getTransformer() { return new PostTransformer(); } public function serializer() { return new \League\Fractal\Serializer\JsonApiSerializer(); } } // Usage // GET /api/posts/1 // Returns: {"data": {"id": 1, "title": "...", "author": {...}}} // GET /api/posts/1?include=author,comments // Returns: {"data": {"id": 1, "...", "author": {...}, "comments": [...]}} ``` -------------------------------- ### Enable ModelFractalPresenter in Repository Source: https://github.com/andersao/l5-repository/blob/master/README.md Configure your repository to use the ModelFractalPresenter by default. ```php use Prettus\Repository\Eloquent\BaseRepository; class PostRepository extends BaseRepository { ... public function presenter() { return "Prettus\\Repository\\Presenter\\ModelFractalPresenter"; } } ``` -------------------------------- ### Create a Repository Source: https://github.com/andersao/l5-repository/blob/master/README.md Extend the BaseRepository and specify the associated Eloquent model class name. ```php namespace App; use Prettus\Repository\Eloquent\BaseRepository; class PostRepository extends BaseRepository { /** * Specify Model class name * * @return string */ function model() { return "App\Post"; } } ``` -------------------------------- ### take Method Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/BaseRepository.md Limits the number of results returned. ```php public function take($limit): $this ``` -------------------------------- ### Artisan Commands for Generating Files Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/README.md Provides a list of Artisan commands to generate various components of the repository pattern, such as models, repositories, presenters, transformers, validators, criteria, and controllers. ```bash # Generate everything for a model php artisan make:entity Post # Generate just repository php artisan make:repository Post # Generate presenter php artisan make:presenter PostPresenter # Generate transformer php artisan make:transformer PostTransformer # Generate validator php artisan make:validator PostValidator # Generate criteria php artisan make:criteria PublishedCriteria # Generate controller php artisan make:controller PostController ``` -------------------------------- ### api-reference/Presenters.md Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Explains the `PresenterInterface` and `PresentableTrait`, detailing Fractal-based transformations, creating custom presenters, and managing presenters on repositories. ```APIDOC ## api-reference/Presenters.md ### Description This document covers the Presenter API, which is used for transforming repository data into a desired format, often for API responses. ### Presenter Details - `PresenterInterface` - Transformation Contract - `PresentableInterface` - Model Presentation - `PresentableTrait` - Default Implementation - `FractalPresenter` - Fractal-based Transformation - `ModelFractalPresenter` - Creating Custom Presenters - Fractal Transformers with Includes - Managing Presenters on Repositories - Configuration - Complete Examples ``` -------------------------------- ### Run RepositoryServiceProvider Test Source: https://github.com/andersao/l5-repository/blob/master/docs/superpowers/plans/2026-05-26-laravel-13-upgrade.md Execute the `RepositoryServiceProviderTest` using `vendor/bin/phpunit` with the `--filter` option. This command isolates and runs the tests for the service provider, ensuring it boots cleanly and registers its components as expected. ```bash vendor/bin/phpunit --filter RepositoryServiceProviderTest ``` -------------------------------- ### api-reference/BaseRepository.md Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Explains the `BaseRepository` abstract implementation, covering its constructor, abstract methods, CRUD operations with validation, advanced where conditions, and criteria management. ```APIDOC ## api-reference/BaseRepository.md ### Description This document details the `BaseRepository` abstract class, which provides a foundational implementation for repositories, including core logic for CRUD operations, validation, events, and criteria management. ### Key Features - Constructor and Initialization - Abstract Methods (`model()`, `presenter()`, `validator()`) - CRUD Operations with Validation and Events - Advanced `where` Conditions (DATE, BETWEEN, IN, EXISTS, HAS) - Criteria Management - Query Constraints and Scoping - Protected Helper Methods - Property Reference - Complete Usage Example ``` -------------------------------- ### Handle QueryException for Nonexistent Column Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/errors.md Catch QueryException when a query fails due to a nonexistent column. This example demonstrates a findWhere call with an invalid column name. ```php $post = $repository->findWhere([ ['nonexistent_column', '=', 'value'] ]); // Throws: Illuminate\Database\QueryException // Column 'nonexistent_column' not found ``` -------------------------------- ### Create a Custom Repository Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/README.md Define a custom repository extending BaseRepository, specifying the model, search fields, and validation rules. ```php namespace App\Repositories; use Prettus\Repository\Eloquent\BaseRepository; use Prettus\Repository\Criteria\RequestCriteria; use Prettus\Validator\Contracts\ValidatorInterface; use App\Models\Post; class PostRepository extends BaseRepository { protected $fieldSearchable = [ 'title' => 'like', 'content' => 'like', 'status' => '=' ]; protected $rules = [ ValidatorInterface::RULE_CREATE => [ 'title' => 'required|string|max:255', 'content' => 'required|string' ], ValidatorInterface::RULE_UPDATE => [ 'title' => 'sometimes|string|max:255' ] ]; public function model() { return Post::class; } public function boot() { $this->pushCriteria(app(RequestCriteria::class)); } } ``` -------------------------------- ### Example: Invalid Input for findWhere Operator Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/errors.md Demonstrates a RepositoryException when the input for operators like 'IN' in findWhere is not an array. Ensure array inputs are provided for these operators. ```php $repository->findWhere([ ['price', 'IN', 'not-an-array'] // IN requires array ]); // Throws: RepositoryException // Message: "Input ... must be an array" ``` ```php $repository->findWhere([ ['price', 'IN', [100, 200, 300]] // Provide array for IN ]); ``` -------------------------------- ### Commit ComparesVersionsTrait Test Source: https://github.com/andersao/l5-repository/blob/master/docs/superpowers/plans/2026-05-26-laravel-13-upgrade.md Stage the newly created `tests/ComparesVersionsTraitTest.php` file and commit it to your repository. Use a commit message that clearly indicates the purpose of the test, such as pinning behavior for an upgrade. ```bash git add tests/ComparesVersionsTraitTest.php git commit -m "test: pin ComparesVersionsTrait behavior for upgrade" ``` -------------------------------- ### Handle QueryException for Integrity Constraint Violation Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/errors.md Catch QueryException for integrity constraint violations, such as foreign key errors. This example attempts to create a post with a non-existent author_id. ```php try { $post = $repository->create([ 'author_id' => 999 // Author doesn't exist (FK constraint) ]); } catch (\Illuminate\Database\QueryException $e) { // "SQLSTATE[HY000]: General error: 1452 Cannot add or update a child row" } ``` -------------------------------- ### Example: Invalid Model Class Configuration Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/errors.md This snippet demonstrates how an incorrect model class configuration in a repository can lead to a RepositoryException. Ensure the model class extends Illuminate\Database\Eloquent\Model. ```php class PostRepository extends BaseRepository { public function model() { return 'App\Post'; // String instead of class name } } // Throws: RepositoryException // Message: "Class App\Post must be an instance of Illuminate\Database\Eloquent\Model" ``` ```php use App\Models\Post; class PostRepository extends BaseRepository { public function model() { return Post::class; // Return FQCN } } ``` -------------------------------- ### Parse Includes Query Parameter Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Presenters.md This configuration defines the query parameter name used for including related data in API requests. It's part of the Fractal setup. ```php protected function parseIncludes(): $this ``` ```php // config/repository.php 'fractal' => [ 'params' => [ 'include' => 'include' // Default query parameter name ] ] ``` -------------------------------- ### Adding Criteria to Repository Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Criteria.md Demonstrates how to add a criteria instance or a criteria class name to a repository for subsequent query application. ```php $repository->pushCriteria(new PublishedCriteria()); $repository->pushCriteria('App\Criteria\ActiveUsersCriteria'); ``` -------------------------------- ### Generate Repository Bindings Source: https://github.com/andersao/l5-repository/blob/master/README.md Use this artisan command to automatically generate the necessary bindings for repositories. ```terminal php artisan make:bindings Cats ``` -------------------------------- ### Publish Configuration File Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/configuration.md Publish the configuration file to your application's config directory using the Artisan command. ```bash php artisan vendor:publish --provider "Prettus\Repository\Providers\RepositoryServiceProvider" ``` -------------------------------- ### Applying Criteria to Repository Queries Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/README.md Shows how to push custom criteria or rely on the built-in RequestCriteria for filtering and sorting. ```php $repository ->pushCriteria(new PublishedCriteria()) ->pushCriteria(new RecentPostsCriteria()) ->paginate(); // Or via HTTP: ?search=laravel&filter=id;title&orderBy=created_at ``` -------------------------------- ### Create New Entry in Repository Source: https://github.com/andersao/l5-repository/blob/master/README.md Creates a new record in the repository using input data. ```php $post = $this->repository->create( Input::all() ); ``` -------------------------------- ### Registering Custom Validation Rule Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Validators.md Extend Laravel's validation capabilities by registering custom rules using Validator::extend. This example shows how to create a unique title validation. ```php class PostValidator extends LaravelValidator { protected $rules = [ ValidatorInterface::RULE_CREATE => [ 'title' => 'required|string|max:255|unique_title', 'slug' => 'required|string|regex:/^[a-z0-9\-]+$/' ] ]; public function boot() { // Register custom rule \Illuminate\Support\Facades\Validator::extend( 'unique_title', function($attribute, $value, $parameters, $validator) { return !Post::where('title', $value) ->where('id', '!=', $this->id ?? 0) ->exists(); }, 'The title must be unique.' ); } } ``` -------------------------------- ### Use Presenter in Controller Source: https://github.com/andersao/l5-repository/blob/master/_autodocs/api-reference/Presenters.md Demonstrates how to use the repository in a controller. The presenter is automatically applied, transforming the output of find() and paginate() methods. ```php class PostController { protected $repository; public function show($id) { return $this->repository->find($id); // Presenter automatically applied, returns transformed data } public function index() { return $this->repository->paginate(); // Collections and pagination handled automatically } } ```