[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-8422":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":16,"stars7d":16,"stars30d":17,"stars90d":16,"forks30d":16,"starsTrendScore":16,"compositeScore":18,"rankGlobal":10,"rankLanguage":10,"license":19,"archived":20,"fork":20,"defaultBranch":21,"hasWiki":22,"hasPages":22,"topics":23,"createdAt":10,"pushedAt":10,"updatedAt":24,"readmeContent":25,"aiSummary":26,"trendingCount":16,"starSnapshotCount":16,"syncStatus":17,"lastSyncTime":27,"discoverSource":28},8422,"l5-repository","andersao\u002Fl5-repository","andersao","Laravel 5 - Repositories to abstract the database layer","http:\u002F\u002Fandersao.github.io\u002Fl5-repository",null,"PHP",4205,893,149,233,0,2,30.85,"MIT License",false,"master",true,[],"2026-06-12 02:01:53","# Laravel 5 Repositories\n\nLaravel 5 Repositories is used to abstract the data layer, making our application more flexible to maintain.\n\n[![Latest Stable Version](https:\u002F\u002Fposer.pugx.org\u002Fprettus\u002Fl5-repository\u002Fv\u002Fstable)](https:\u002F\u002Fpackagist.org\u002Fpackages\u002Fprettus\u002Fl5-repository) [![Total Downloads](https:\u002F\u002Fposer.pugx.org\u002Fprettus\u002Fl5-repository\u002Fdownloads)](https:\u002F\u002Fpackagist.org\u002Fpackages\u002Fprettus\u002Fl5-repository) [![Latest Unstable Version](https:\u002F\u002Fposer.pugx.org\u002Fprettus\u002Fl5-repository\u002Fv\u002Funstable)](https:\u002F\u002Fpackagist.org\u002Fpackages\u002Fprettus\u002Fl5-repository) [![License](https:\u002F\u002Fposer.pugx.org\u002Fprettus\u002Fl5-repository\u002Flicense)](https:\u002F\u002Fpackagist.org\u002Fpackages\u002Fprettus\u002Fl5-repository)\n[![Analytics](https:\u002F\u002Fga-beacon.appspot.com\u002FUA-61050740-1\u002Fl5-repository\u002Freadme)](https:\u002F\u002Fpackagist.org\u002Fpackages\u002Fprettus\u002Fl5-repository)\n[![Code Climate](https:\u002F\u002Fcodeclimate.com\u002Fgithub\u002Fandersao\u002Fl5-repository\u002Fbadges\u002Fgpa.svg)](https:\u002F\u002Fcodeclimate.com\u002Fgithub\u002Fandersao\u002Fl5-repository)\n\n#### See versions: [1.0.*](https:\u002F\u002Fgithub.com\u002Fandersao\u002Fl5-repository\u002Ftree\u002F1.0.4) \u002F [2.0.*](https:\u002F\u002Fgithub.com\u002Fandersao\u002Fl5-repository\u002Ftree\u002F2.0.14)\n#### Migrate to: [2.0](migration-to-2.0.md) \u002F [2.1](migration-to-2.1.md)\n\nYou want to know a little more about the Repository pattern? [Read this great article](http:\u002F\u002Fbit.ly\u002F1IdmRNS).\n\n## Table of Contents\n\n- \u003Ca href=\"#installation\">Installation\u003C\u002Fa>\n    - \u003Ca href=\"#composer\">Composer\u003C\u002Fa>\n    - \u003Ca href=\"#laravel\">Laravel\u003C\u002Fa>\n- \u003Ca href=\"#methods\">Methods\u003C\u002Fa>\n    - \u003Ca href=\"#prettusrepositorycontractsrepositoryinterface\">RepositoryInterface\u003C\u002Fa>\n    - \u003Ca href=\"#prettusrepositorycontractsrepositorycriteriainterface\">RepositoryCriteriaInterface\u003C\u002Fa>\n    - \u003Ca href=\"#prettusrepositorycontractscacheableinterface\">CacheableInterface\u003C\u002Fa>\n    - \u003Ca href=\"#prettusrepositorycontractspresenterinterface\">PresenterInterface\u003C\u002Fa>\n    - \u003Ca href=\"#prettusrepositorycontractscriteriainterface\">CriteriaInterface\u003C\u002Fa>\n- \u003Ca href=\"#usage\">Usage\u003C\u002Fa>\n\t- \u003Ca href=\"#create-a-model\">Create a Model\u003C\u002Fa>\n\t- \u003Ca href=\"#create-a-repository\">Create a Repository\u003C\u002Fa>\n\t- \u003Ca href=\"#generators\">Generators\u003C\u002Fa>\n\t- \u003Ca href=\"#use-methods\">Use methods\u003C\u002Fa>\n\t- \u003Ca href=\"#create-a-criteria\">Create a Criteria\u003C\u002Fa>\n\t- \u003Ca href=\"#using-the-criteria-in-a-controller\">Using the Criteria in a Controller\u003C\u002Fa>\n\t- \u003Ca href=\"#using-the-requestcriteria\">Using the RequestCriteria\u003C\u002Fa>\n- \u003Ca href=\"#cache\">Cache\u003C\u002Fa>\n    - \u003Ca href=\"#cache-usage\">Usage\u003C\u002Fa>\n    - \u003Ca href=\"#cache-config\">Config\u003C\u002Fa>\n- \u003Ca href=\"#validators\">Validators\u003C\u002Fa>\n    - \u003Ca href=\"#using-a-validator-class\">Using a Validator Class\u003C\u002Fa>\n        - \u003Ca href=\"#create-a-validator\">Create a Validator\u003C\u002Fa>\n        - \u003Ca href=\"#enabling-validator-in-your-repository-1\">Enabling Validator in your Repository\u003C\u002Fa>\n    - \u003Ca href=\"#defining-rules-in-the-repository\">Defining rules in the repository\u003C\u002Fa>\n- \u003Ca href=\"#presenters\">Presenters\u003C\u002Fa>\n    - \u003Ca href=\"#fractal-presenter\">Fractal Presenter\u003C\u002Fa>\n        - \u003Ca href=\"#create-a-presenter\">Create a Fractal Presenter\u003C\u002Fa>\n        - \u003Ca href=\"#implement-interface\">Model Transformable\u003C\u002Fa>\n    - \u003Ca href=\"#enabling-in-your-repository-1\">Enabling in your Repository\u003C\u002Fa>\n\n## Installation\n\n### Composer\n\nExecute the following command to get the latest version of the package:\n\n```terminal\ncomposer require prettus\u002Fl5-repository\n```\n\n### Laravel\n\n#### >= laravel5.5\n\nServiceProvider will be attached automatically\n\n#### Other\n\nIn your `config\u002Fapp.php` add `Prettus\\Repository\\Providers\\RepositoryServiceProvider::class` to the end of the `providers` array:\n\n```php\n'providers' => [\n    ...\n    Prettus\\Repository\\Providers\\RepositoryServiceProvider::class,\n],\n```\n\nIf Lumen\n\n```php\n$app->register(Prettus\\Repository\\Providers\\LumenRepositoryServiceProvider::class);\n```\n\nPublish Configuration\n\n```shell\nphp artisan vendor:publish --provider \"Prettus\\Repository\\Providers\\RepositoryServiceProvider\"\n```\n\n## Methods\n\n### Prettus\\Repository\\Contracts\\RepositoryInterface\n\n- all($columns = array('*'))\n- first($columns = array('*'))\n- paginate($limit = null, $columns = ['*'])\n- find($id, $columns = ['*'])\n- findByField($field, $value, $columns = ['*'])\n- findWhere(array $where, $columns = ['*'])\n- findWhereIn($field, array $where, $columns = [*])\n- findWhereNotIn($field, array $where, $columns = [*])\n- findWhereBetween($field, array $where, $columns = [*])\n- create(array $attributes)\n- update(array $attributes, $id)\n- updateOrCreate(array $attributes, array $values = [])\n- delete($id)\n- deleteWhere(array $where)\n- orderBy($column, $direction = 'asc');\n- with(array $relations);\n- has(string $relation);\n- whereHas(string $relation, closure $closure);\n- hidden(array $fields);\n- visible(array $fields);\n- scopeQuery(Closure $scope);\n- getFieldsSearchable();\n- setPresenter($presenter);\n- skipPresenter($status = true);\n\n\n### Prettus\\Repository\\Contracts\\RepositoryCriteriaInterface\n\n- pushCriteria($criteria)\n- popCriteria($criteria)\n- getCriteria()\n- getByCriteria(CriteriaInterface $criteria)\n- skipCriteria($status = true)\n- getFieldsSearchable()\n\n### Prettus\\Repository\\Contracts\\CacheableInterface\n\n- setCacheRepository(CacheRepository $repository)\n- getCacheRepository()\n- getCacheKey($method, $args = null)\n- getCacheTime()\n- skipCache($status = true)\n\n### Prettus\\Repository\\Contracts\\PresenterInterface\n\n- present($data);\n\n### Prettus\\Repository\\Contracts\\Presentable\n\n- setPresenter(PresenterInterface $presenter);\n- presenter();\n\n### Prettus\\Repository\\Contracts\\CriteriaInterface\n\n- apply($model, RepositoryInterface $repository);\n\n### Prettus\\Repository\\Contracts\\Transformable\n\n- transform();\n\n\n## Usage\n\n### Create a Model\n\nCreate your model normally, but it is important to define the attributes that can be filled from the input form data.\n\n```php\nnamespace App;\n\nclass Post extends Eloquent { \u002F\u002F or Ardent, Or any other Model Class\n\n    protected $fillable = [\n        'title',\n        'author',\n        ...\n     ];\n\n     ...\n}\n```\n\n### Create a Repository\n\n```php\nnamespace App;\n\nuse Prettus\\Repository\\Eloquent\\BaseRepository;\n\nclass PostRepository extends BaseRepository {\n\n    \u002F**\n     * Specify Model class name\n     *\n     * @return string\n     *\u002F\n    function model()\n    {\n        return \"App\\\\Post\";\n    }\n}\n```\n\n### Generators\n\nCreate your repositories easily through the generator.\n\n#### Config\n\nYou must first configure the storage location of the repository files. By default is the \"app\" folder and the namespace \"App\". Please note that, values in the `paths` array are acutally used as both *namespace* and file paths. Relax though, both foreward and backward slashes are taken care of during generation.\n\n```php\n    ...\n    'generator'=>[\n        'basePath'=>app()->path(),\n        'rootNamespace'=>'App\\\\',\n        'paths'=>[\n            'models'       => 'Entities',\n            'repositories' => 'Repositories',\n            'interfaces'   => 'Repositories',\n            'transformers' => 'Transformers',\n            'presenters'   => 'Presenters',\n            'validators'   => 'Validators',\n            'controllers'  => 'Http\u002FControllers',\n            'provider'     => 'RepositoryServiceProvider',\n            'criteria'     => 'Criteria',\n        ]\n    ]\n```\n\nYou may want to save the root of your project folder out of the app and add another namespace, for example\n\n```php\n    ...\n     'generator'=>[\n        'basePath'      => base_path('src\u002FLorem'),\n        'rootNamespace' => 'Lorem\\\\'\n    ]\n```\n\nAdditionally, you may wish to customize where your generated classes end up being saved.  That can be accomplished by editing the `paths` node to your liking.  For example:\n\n```php\n    'generator'=>[\n        'basePath'=>app()->path(),\n        'rootNamespace'=>'App\\\\',\n        'paths'=>[\n            'models'=>'Models',\n            'repositories'=>'Repositories\\\\Eloquent',\n            'interfaces'=>'Contracts\\\\Repositories',\n            'transformers'=>'Transformers',\n            'presenters'=>'Presenters'\n            'validators'   => 'Validators',\n            'controllers'  => 'Http\u002FControllers',\n            'provider'     => 'RepositoryServiceProvider',\n            'criteria'     => 'Criteria',\n        ]\n    ]\n```\n\n#### Commands\n\nTo generate everything you need for your Model, run this command:\n\n```terminal\nphp artisan make:entity Post\n```\n\nThis will create the Controller, the Validator, the Model, the Repository, the Presenter and the Transformer classes.\nIt will also create a new service provider that will be used to bind the Eloquent Repository with its corresponding Repository Interface.\nTo load it, just add this to your AppServiceProvider@register method:\n\n```php\n    $this->app->register(RepositoryServiceProvider::class);\n```\n\nYou can also pass the options from the ```repository``` command, since this command is just a wrapper.\n\nTo generate a repository for your Post model, use the following command\n\n```terminal\nphp artisan make:repository Post\n```\n\nTo generate a repository for your Post model with Blog namespace, use the following command\n\n```terminal\nphp artisan make:repository \"Blog\\Post\"\n```\n\nAdded fields that are fillable\n\n```terminal\nphp artisan make:repository \"Blog\\Post\" --fillable=\"title,content\"\n```\n\nTo add validations rules directly with your command you need to pass the `--rules` option and create migrations as well:\n\n```terminal\nphp artisan make:entity Cat --fillable=\"title:string,content:text\" --rules=\"title=>required|min:2, content=>sometimes|min:10\"\n```\n\nThe command will also create your basic RESTfull controller so just add this line into your `routes.php` file and you will have a basic CRUD:\n\n ```php\n Route::resource('cats', CatsController::class);\n ```\n\nWhen running the command, you will be creating the \"Entities\" folder and \"Repositories\" inside the folder that you set as the default.\n\nNow that is done, you still need to bind its interface for your real repository, for example in your own Repositories Service Provider.\n\n```php\nApp::bind('{YOUR_NAMESPACE}Repositories\\PostRepository', '{YOUR_NAMESPACE}Repositories\\PostRepositoryEloquent');\n```\n\nAnd use\n\n```php\npublic function __construct({YOUR_NAMESPACE}Repositories\\PostRepository $repository){\n    $this->repository = $repository;\n}\n```\n\nAlternatively, you could use the artisan command to do the binding for you.\n\n```php\nphp artisan make:bindings Cats\n```\n\n### Use methods\n\n```php\nnamespace App\\Http\\Controllers;\n\nuse App\\PostRepository;\n\nclass PostsController extends BaseController {\n\n    \u002F**\n     * @var PostRepository\n     *\u002F\n    protected $repository;\n\n    public function __construct(PostRepository $repository){\n        $this->repository = $repository;\n    }\n\n    ....\n}\n```\n\nFind all results in Repository\n\n```php\n$posts = $this->repository->all();\n```\n\nFind all results in Repository with pagination\n\n```php\n$posts = $this->repository->paginate($limit = null, $columns = ['*']);\n```\n\nFind by result by id\n\n```php\n$post = $this->repository->find($id);\n```\n\nHiding attributes of the model\n\n```php\n$post = $this->repository->hidden(['country_id'])->find($id);\n```\n\nShowing only specific attributes of the model\n\n```php\n$post = $this->repository->visible(['id', 'state_id'])->find($id);\n```\n\nLoading the Model relationships\n\n```php\n$post = $this->repository->with(['state'])->find($id);\n```\n\nFind by result by field name\n\n```php\n$posts = $this->repository->findByField('country_id','15');\n```\n\nFind by result by multiple fields\n\n```php\n$posts = $this->repository->findWhere([\n    \u002F\u002FDefault Condition =\n    'state_id'=>'10',\n    'country_id'=>'15',\n\n    \u002F\u002FCustom Condition\n    ['columnName1','>','10'],\n\n    \u002F\u002FDATE, DAY, MONTH, YEAR\n    ['columnName2','DATE','2021-07-02'], \u002F\u002FwhereDate\n    ['columnName3','DATE >=','2021-07-02'], \u002F\u002FwhereDate with operator\n\n    ['columnName4','IN',['value1','value2']], \u002F\u002FwhereIn\n    ['columnName5','NOTIN',['value1','value2']], \u002F\u002FwhereNotIn\n    ['columnName6','EXIST',''], \u002F\u002FwhereExists\n    \n    \u002F\u002FHAS, HASMORPH, DOESNTHAVE, DOESNTHAVEMORPH\n    ['columnName7','HAS',function($query){}], \u002F\u002FwhereHas\n\n    \u002F\u002FBETWEEN, BETWEENCOLUMNS, NOTBETWEEN, NOTBETWEENCOLUMNS\n    ['columnName8','BETWEEN',[10, 100]], \u002F\u002FwhereBetween\n]);\n```\n\nFind by result by multiple values in one field\n\n```php\n$posts = $this->repository->findWhereIn('id', [1,2,3,4,5]);\n```\n\nFind by result by excluding multiple values in one field\n\n```php\n$posts = $this->repository->findWhereNotIn('id', [6,7,8,9,10]);\n```\n\nFind all using custom scope\n\n```php\n$posts = $this->repository->scopeQuery(function($query){\n    return $query->orderBy('sort_order','asc');\n})->all();\n```\n\nCreate new entry in Repository\n\n```php\n$post = $this->repository->create( Input::all() );\n```\n\nUpdate entry in Repository\n\n```php\n$post = $this->repository->update( Input::all(), $id );\n```\n\nDelete entry in Repository\n\n```php\n$this->repository->delete($id)\n```\n\nDelete entry in Repository by multiple fields\n\n```php\n$this->repository->deleteWhere([\n    \u002F\u002FDefault Condition =\n    'state_id'=>'10',\n    'country_id'=>'15',\n])\n```\n\n### Create a Criteria\n\n#### Using the command\n\n```terminal\nphp artisan make:criteria MyCriteria\n```\n\nCriteria are a way to change the repository of the query by applying specific conditions according to your needs. You can add multiple Criteria in your repository.\n\n```php\n\nuse Prettus\\Repository\\Contracts\\RepositoryInterface;\nuse Prettus\\Repository\\Contracts\\CriteriaInterface;\n\nclass MyCriteria implements CriteriaInterface {\n\n    public function apply($model, RepositoryInterface $repository)\n    {\n        $model = $model->where('user_id','=', Auth::user()->id );\n        return $model;\n    }\n}\n```\n\n### Using the Criteria in a Controller\n\n```php\n\nnamespace App\\Http\\Controllers;\n\nuse App\\PostRepository;\n\nclass PostsController extends BaseController {\n\n    \u002F**\n     * @var PostRepository\n     *\u002F\n    protected $repository;\n\n    public function __construct(PostRepository $repository){\n        $this->repository = $repository;\n    }\n\n\n    public function index()\n    {\n        $this->repository->pushCriteria(new MyCriteria1());\n        $this->repository->pushCriteria(MyCriteria2::class);\n        $posts = $this->repository->all();\n\t\t...\n    }\n\n}\n```\n\nGetting results from Criteria\n\n```php\n$posts = $this->repository->getByCriteria(new MyCriteria());\n```\n\nSetting the default Criteria in Repository\n\n```php\nuse Prettus\\Repository\\Eloquent\\BaseRepository;\n\nclass PostRepository extends BaseRepository {\n\n    public function boot(){\n        $this->pushCriteria(new MyCriteria());\n        \u002F\u002F or\n        $this->pushCriteria(AnotherCriteria::class);\n        ...\n    }\n\n    function model(){\n       return \"App\\\\Post\";\n    }\n}\n```\n\n### Skip criteria defined in the repository\n\nUse `skipCriteria` before any other chaining method\n\n```php\n$posts = $this->repository->skipCriteria()->all();\n```\n\n### Popping criteria\n\nUse `popCriteria` to remove a criteria\n\n```php\n$this->repository->popCriteria(new Criteria1());\n\u002F\u002F or\n$this->repository->popCriteria(Criteria1::class);\n```\n\n\n### Using the RequestCriteria\n\nRequestCriteria is a standard Criteria implementation. It enables filters to perform in the repository from parameters sent in the request.\n\nYou can perform a dynamic search, filter the data and customize the queries.\n\nTo use the Criteria in your repository, you can add a new criteria in the boot method of your repository, or directly use in your controller, in order to filter out only a few requests.\n\n#### Enabling in your Repository\n\n```php\nuse Prettus\\Repository\\Eloquent\\BaseRepository;\nuse Prettus\\Repository\\Criteria\\RequestCriteria;\n\n\nclass PostRepository extends BaseRepository {\n\n\t\u002F**\n     * @var array\n     *\u002F\n    protected $fieldSearchable = [\n        'name',\n        'email'\n    ];\n\n    public function boot(){\n        $this->pushCriteria(app('Prettus\\Repository\\Criteria\\RequestCriteria'));\n        ...\n    }\n\n    function model(){\n       return \"App\\\\Post\";\n    }\n}\n```\n\nRemember, you need to define which fields from the model can be searchable.\n\nIn your repository set **$fieldSearchable** with the name of the fields to be searchable or a relation to fields.\n\n```php\nprotected $fieldSearchable = [\n\t'name',\n\t'email',\n\t'product.name'\n];\n```\n\nYou can set the type of condition which will be used to perform the query, the default condition is \"**=**\"\n\n```php\nprotected $fieldSearchable = [\n\t'name'=>'like',\n\t'email', \u002F\u002F Default Condition \"=\"\n\t'your_field'=>'condition'\n];\n```\n\n\n#### Enabling in your Controller\n\n```php\n\tpublic function index()\n    {\n        $this->repository->pushCriteria(app('Prettus\\Repository\\Criteria\\RequestCriteria'));\n        $posts = $this->repository->all();\n\t\t...\n    }\n```\n\n#### Example the Criteria\n\nRequest all data without filter by request\n\n`http:\u002F\u002Fprettus.local\u002Fusers`\n\n```json\n[\n    {\n        \"id\": 1,\n        \"name\": \"John Doe\",\n        \"email\": \"john@gmail.com\",\n        \"created_at\": \"-0001-11-30 00:00:00\",\n        \"updated_at\": \"-0001-11-30 00:00:00\"\n    },\n    {\n        \"id\": 2,\n        \"name\": \"Lorem Ipsum\",\n        \"email\": \"lorem@ipsum.com\",\n        \"created_at\": \"-0001-11-30 00:00:00\",\n        \"updated_at\": \"-0001-11-30 00:00:00\"\n    },\n    {\n        \"id\": 3,\n        \"name\": \"Laravel\",\n        \"email\": \"laravel@gmail.com\",\n        \"created_at\": \"-0001-11-30 00:00:00\",\n        \"updated_at\": \"-0001-11-30 00:00:00\"\n    }\n]\n```\n\nConducting research in the repository\n\n`http:\u002F\u002Fprettus.local\u002Fusers?search=John%20Doe`\n\nor\n\n`http:\u002F\u002Fprettus.local\u002Fusers?search=John&searchFields=name:like`\n\nor\n\n`http:\u002F\u002Fprettus.local\u002Fusers?search=john@gmail.com&searchFields=email:=`\n\nor\n\n`http:\u002F\u002Fprettus.local\u002Fusers?search=name:John Doe;email:john@gmail.com`\n\nor\n\n`http:\u002F\u002Fprettus.local\u002Fusers?search=name:John;email:john@gmail.com&searchFields=name:like;email:=`\n\n```json\n[\n    {\n        \"id\": 1,\n        \"name\": \"John Doe\",\n        \"email\": \"john@gmail.com\",\n        \"created_at\": \"-0001-11-30 00:00:00\",\n        \"updated_at\": \"-0001-11-30 00:00:00\"\n    }\n]\n```\n\nYou can use params \"search\" without full params \"searchFields\".\n\n`http:\u002F\u002Fprettus.local\u002Fusers?search=id:2;age:17;email:john@gmail.com&searchFields='id':=`\n\nBy default RequestCriteria makes its queries using the **OR** comparison operator for each query parameter.\n`http:\u002F\u002Fprettus.local\u002Fusers?search=age:17;email:john@gmail.com`\n\nThe above example will execute the following query:\n``` sql\nSELECT * FROM users WHERE age = 17 OR email = 'john@gmail.com';\n```\n\nIn order for it to query using the **AND**, pass the *searchJoin* parameter as shown below:\n\n`http:\u002F\u002Fprettus.local\u002Fusers?search=age:17;email:john@gmail.com&searchJoin=and`\n\n\n\n\n\nFiltering fields\n\n`http:\u002F\u002Fprettus.local\u002Fusers?filter=id;name`\n\n```json\n[\n    {\n        \"id\": 1,\n        \"name\": \"John Doe\"\n    },\n    {\n        \"id\": 2,\n        \"name\": \"Lorem Ipsum\"\n    },\n    {\n        \"id\": 3,\n        \"name\": \"Laravel\"\n    }\n]\n```\n\nSorting the results\n\n`http:\u002F\u002Fprettus.local\u002Fusers?filter=id;name&orderBy=id&sortedBy=desc`\n\n```json\n[\n    {\n        \"id\": 3,\n        \"name\": \"Laravel\"\n    },\n    {\n        \"id\": 2,\n        \"name\": \"Lorem Ipsum\"\n    },\n    {\n        \"id\": 1,\n        \"name\": \"John Doe\"\n    }\n]\n```\n\nSorting through related tables\n\n`http:\u002F\u002Fprettus.local\u002Fusers?orderBy=posts|title&sortedBy=desc`\n\nQuery will have something like this\n\n```sql\n...\nINNER JOIN posts ON users.post_id = posts.id\n...\nORDER BY title\n...\n```\n\n`http:\u002F\u002Fprettus.local\u002Fusers?orderBy=posts:custom_id|posts.title&sortedBy=desc`\n\nQuery will have something like this\n\n```sql\n...\nINNER JOIN posts ON users.custom_id = posts.id\n...\nORDER BY posts.title\n...\n```\n\n`http:\u002F\u002Fprettus.local\u002Fusers?orderBy=posts:custom_id,other_id|posts.title&sortedBy=desc`\n\nQuery will have something like this\n\n```sql\n...\nINNER JOIN posts ON users.custom_id = posts.other_id\n...\nORDER BY posts.title\n...\n```\n\nSorting multiple columns same sortedBy\n\n`http:\u002F\u002Fprettus.local\u002Fusers?orderBy=name;created_at&sortedBy=desc`\n\nResult will have something like this\n\n```json\n   [\n       {\n           \"id\": 1,\n           \"name\": \"Laravel\",\n           \"created_at\": \"-0001-11-29 00:00:00\"\n       },\n       {\n           \"id\": 3,\n           \"name\": \"Laravel\",\n           \"created_at\": \"-0001-11-28 00:00:00\"\n       },\n       {\n           \"id\": 2,\n           \"name\": \"John Doe\",\n           \"created_at\": \"-0001-11-30 00:00:00\"\n       }\n   ]\n```\n\n\nSorting multiple columns difference sortedBy\n\n`http:\u002F\u002Fprettus.local\u002Fusers?orderBy=name;created_at&sortedBy=desc;asc`\n\nResult will have something like this\n\n```json\n   [\n       {\n           \"id\": 3,\n           \"name\": \"Laravel\",\n           \"created_at\": \"-0001-11-28 00:00:00\"\n       },\n       {\n           \"id\": 1,\n           \"name\": \"Laravel\",\n           \"created_at\": \"-0001-11-29 00:00:00\"\n       },\n       {\n           \"id\": 2,\n           \"name\": \"John Doe\",\n           \"created_at\": \"-0001-11-30 00:00:00\"\n       }\n   ]\n```\n\nAdd relationship\n\n`http:\u002F\u002Fprettus.local\u002Fusers?with=groups`\n\nBetween filter\n\n`http:\u002F\u002Fprettus.local\u002Fproduct?search=price:100,500&searchFields=price:between`\n\nResult will have something like this\n\n```json\n   [\n       {\n           \"id\": 3,\n           \"price\": \"150\",\n           \"created_at\": \"-0001-11-28 00:00:00\"\n       },\n       {\n           \"id\": 1,\n           \"price\": \"300\",\n           \"created_at\": \"-0001-11-29 00:00:00\"\n       },\n       {\n           \"id\": 2,\n           \"price\": \"450\",\n           \"created_at\": \"-0001-11-30 00:00:00\"\n       }\n   ]\n```\n\nWhereIn filter\n\n`http:\u002F\u002Fprettus.local\u002Fproduct?search=price:300,500&searchFields=price:in`\n\nResult will have something like this\n\n```json\n   [\n       {\n           \"id\": 1,\n           \"price\": \"300\",\n           \"created_at\": \"-0001-11-29 00:00:00\"\n       }\n   ]\n```\n\n#### Overwrite params name\n\nYou can change the name of the parameters in the configuration file **config\u002Frepository.php**\n\n### Cache\n\nAdd a layer of cache easily to your repository\n\n#### Cache Usage\n\nImplements the interface CacheableInterface and use CacheableRepository Trait.\n\n```php\nuse Prettus\\Repository\\Eloquent\\BaseRepository;\nuse Prettus\\Repository\\Contracts\\CacheableInterface;\nuse Prettus\\Repository\\Traits\\CacheableRepository;\n\nclass PostRepository extends BaseRepository implements CacheableInterface {\n\n    use CacheableRepository;\n\n    ...\n}\n```\n\nDone , done that your repository will be cached , and the repository cache is cleared whenever an item is created, modified or deleted.\n\n#### Cache Config\n\nYou can change the cache settings in the file *config\u002Frepository.php* and also directly on your repository.\n\n*config\u002Frepository.php*\n\n```php\n'cache'=>[\n    \u002F\u002FEnable or disable cache repositories\n    'enabled'   => true,\n\n    \u002F\u002FLifetime of cache\n    'minutes'   => 30,\n\n    \u002F\u002FRepository Cache, implementation Illuminate\\Contracts\\Cache\\Repository\n    'repository'=> 'cache',\n\n    \u002F\u002FSets clearing the cache\n    'clean'     => [\n        \u002F\u002FEnable, disable clearing the cache on changes\n        'enabled' => true,\n\n        'on' => [\n            \u002F\u002FEnable, disable clearing the cache when you create an item\n            'create'=>true,\n\n            \u002F\u002FEnable, disable clearing the cache when upgrading an item\n            'update'=>true,\n\n            \u002F\u002FEnable, disable clearing the cache when you delete an item\n            'delete'=>true,\n        ]\n    ],\n    'params' => [\n        \u002F\u002FRequest parameter that will be used to bypass the cache repository\n        'skipCache'=>'skipCache'\n    ],\n    'allowed'=>[\n        \u002F\u002FAllow caching only for some methods\n        'only'  =>null,\n\n        \u002F\u002FAllow caching for all available methods, except\n        'except'=>null\n    ],\n],\n```\n\nIt is possible to override these settings directly in the repository.\n\n```php\nuse Prettus\\Repository\\Eloquent\\BaseRepository;\nuse Prettus\\Repository\\Contracts\\CacheableInterface;\nuse Prettus\\Repository\\Traits\\CacheableRepository;\n\nclass PostRepository extends BaseRepository implements CacheableInterface {\n\n    \u002F\u002F Setting the lifetime of the cache to a repository specifically\n    protected $cacheMinutes = 90;\n\n    protected $cacheOnly = ['all', ...];\n    \u002F\u002For\n    protected $cacheExcept = ['find', ...];\n\n    use CacheableRepository;\n\n    ...\n}\n```\n\nThe cacheable methods are : all, paginate, find, findByField, findWhere, getByCriteria\n\n### Validators\n\nRequires [prettus\u002Flaravel-validator](https:\u002F\u002Fgithub.com\u002Fprettus\u002Flaravel-validator). `composer require prettus\u002Flaravel-validator`\n\nEasy validation with `prettus\u002Flaravel-validator`\n\n[For more details click here](https:\u002F\u002Fgithub.com\u002Fprettus\u002Flaravel-validator)\n\n#### Using a Validator Class\n\n##### Create a Validator\n\nIn the example below, we define some rules for both creation and edition\n\n```php\nuse \\Prettus\\Validator\\LaravelValidator;\n\nclass PostValidator extends LaravelValidator {\n\n    protected $rules = [\n        'title' => 'required',\n        'text'  => 'min:3',\n        'author'=> 'required'\n    ];\n\n}\n```\n\nTo define specific rules, proceed as shown below:\n\n```php\nuse \\Prettus\\Validator\\Contracts\\ValidatorInterface;\nuse \\Prettus\\Validator\\LaravelValidator;\n\nclass PostValidator extends LaravelValidator {\n\n    protected $rules = [\n        ValidatorInterface::RULE_CREATE => [\n            'title' => 'required',\n            'text'  => 'min:3',\n            'author'=> 'required'\n        ],\n        ValidatorInterface::RULE_UPDATE => [\n            'title' => 'required'\n        ]\n   ];\n\n}\n```\n\n##### Enabling Validator in your Repository\n\n```php\nuse Prettus\\Repository\\Eloquent\\BaseRepository;\nuse Prettus\\Repository\\Criteria\\RequestCriteria;\n\nclass PostRepository extends BaseRepository {\n\n    \u002F**\n     * Specify Model class name\n     *\n     * @return mixed\n     *\u002F\n    function model(){\n       return \"App\\\\Post\";\n    }\n\n    \u002F**\n     * Specify Validator class name\n     *\n     * @return mixed\n     *\u002F\n    public function validator()\n    {\n        return \"App\\\\PostValidator\";\n    }\n}\n```\n\n#### Defining rules in the repository\n\nAlternatively, instead of using a class to define its validation rules, you can set your rules directly into the rules repository property, it will have the same effect as a Validation class.\n\n```php\nuse Prettus\\Repository\\Eloquent\\BaseRepository;\nuse Prettus\\Repository\\Criteria\\RequestCriteria;\nuse Prettus\\Validator\\Contracts\\ValidatorInterface;\n\nclass PostRepository extends BaseRepository {\n\n    \u002F**\n     * Specify Validator Rules\n     * @var array\n     *\u002F\n     protected $rules = [\n        ValidatorInterface::RULE_CREATE => [\n            'title' => 'required',\n            'text'  => 'min:3',\n            'author'=> 'required'\n        ],\n        ValidatorInterface::RULE_UPDATE => [\n            'title' => 'required'\n        ]\n   ];\n\n    \u002F**\n     * Specify Model class name\n     *\n     * @return mixed\n     *\u002F\n    function model(){\n       return \"App\\\\Post\";\n    }\n\n}\n```\n\nValidation is now ready. In case of a failure an exception will be given of the type: *Prettus\\Validator\\Exceptions\\ValidatorException*\n\n### Presenters\n\nPresenters function as a wrapper and renderer for objects.\n\n#### Fractal Presenter\n\nRequires [Fractal](http:\u002F\u002Ffractal.thephpleague.com\u002F). `composer require league\u002Ffractal`\n\nThere are two ways to implement the Presenter, the first is creating a TransformerAbstract and set it using your Presenter class as described in the Create a Transformer Class.\n\nThe second way is to make your model implement the Transformable interface, and use the default Presenter ModelFractarPresenter, this will have the same effect.\n\n##### Transformer Class\n\n###### Create a Transformer using the command\n\n```terminal\nphp artisan make:transformer Post\n```\n\nThis will generate the class beneath.\n\n###### Create a Transformer Class\n\n```php\nuse League\\Fractal\\TransformerAbstract;\n\nclass PostTransformer extends TransformerAbstract\n{\n    public function transform(\\Post $post)\n    {\n        return [\n            'id'      => (int) $post->id,\n            'title'   => $post->title,\n            'content' => $post->content\n        ];\n    }\n}\n```\n\n###### Create a Presenter using the command\n\n```terminal\nphp artisan make:presenter Post\n```\n\nThe command will prompt you for creating a Transformer too if you haven't already.\n###### Create a Presenter\n\n```php\nuse Prettus\\Repository\\Presenter\\FractalPresenter;\n\nclass PostPresenter extends FractalPresenter {\n\n    \u002F**\n     * Prepare data to present\n     *\n     * @return \\League\\Fractal\\TransformerAbstract\n     *\u002F\n    public function getTransformer()\n    {\n        return new PostTransformer();\n    }\n}\n```\n\n###### Enabling in your Repository\n\n```php\nuse Prettus\\Repository\\Eloquent\\BaseRepository;\n\nclass PostRepository extends BaseRepository {\n\n    ...\n\n    public function presenter()\n    {\n        return \"App\\\\Presenter\\\\PostPresenter\";\n    }\n}\n```\n\nOr enable it in your controller with\n\n```php\n$this->repository->setPresenter(\"App\\\\Presenter\\\\PostPresenter\");\n```\n\n###### Using the presenter after from the Model\n\nIf you recorded a presenter and sometime used the `skipPresenter()` method or simply you do not want your result is not changed automatically by the presenter.\nYou can implement Presentable interface on your model so you will be able to present your model at any time. See below:\n\nIn your model, implement the interface `Prettus\\Repository\\Contracts\\Presentable` and `Prettus\\Repository\\Traits\\PresentableTrait`\n\n```php\nnamespace App;\n\nuse Prettus\\Repository\\Contracts\\Presentable;\nuse Prettus\\Repository\\Traits\\PresentableTrait;\n\nclass Post extends Eloquent implements Presentable {\n\n    use PresentableTrait;\n\n    protected $fillable = [\n        'title',\n        'author',\n        ...\n     ];\n\n     ...\n}\n```\n\nThere, now you can submit your Model individually, See an example:\n\n```php\n$repository = app('App\\PostRepository');\n$repository->setPresenter(\"Prettus\\\\Repository\\\\Presenter\\\\ModelFractalPresenter\");\n\n\u002F\u002FGetting the result transformed by the presenter directly in the search\n$post = $repository->find(1);\n\nprint_r( $post ); \u002F\u002FIt produces an output as array\n\n...\n\n\u002F\u002FSkip presenter and bringing the original result of the Model\n$post = $repository->skipPresenter()->find(1);\n\nprint_r( $post ); \u002F\u002FIt produces an output as a Model object\nprint_r( $post->presenter() ); \u002F\u002FIt produces an output as array\n\n```\n\nYou can skip the presenter at every visit and use it on demand directly into the model, for it set the `$skipPresenter` attribute to true in your repository:\n\n```php\nuse Prettus\\Repository\\Eloquent\\BaseRepository;\n\nclass PostRepository extends BaseRepository {\n\n    \u002F**\n    * @var bool\n    *\u002F\n    protected $skipPresenter = true;\n\n    public function presenter()\n    {\n        return \"App\\\\Presenter\\\\PostPresenter\";\n    }\n}\n```\n\n##### Model Class\n\n###### Implement Interface\n\n```php\nnamespace App;\n\nuse Prettus\\Repository\\Contracts\\Transformable;\n\nclass Post extends Eloquent implements Transformable {\n     ...\n     \u002F**\n      * @return array\n      *\u002F\n     public function transform()\n     {\n         return [\n             'id'      => (int) $this->id,\n             'title'   => $this->title,\n             'content' => $this->content\n         ];\n     }\n}\n```\n\n###### Enabling in your Repository\n\n`Prettus\\Repository\\Presenter\\ModelFractalPresenter` is a Presenter default for Models implementing Transformable\n\n```php\nuse Prettus\\Repository\\Eloquent\\BaseRepository;\n\nclass PostRepository extends BaseRepository {\n\n    ...\n\n    public function presenter()\n    {\n        return \"Prettus\\\\Repository\\\\Presenter\\\\ModelFractalPresenter\";\n    }\n}\n```\n\nOr enable it in your controller with\n\n```php\n$this->repository->setPresenter(\"Prettus\\\\Repository\\\\Presenter\\\\ModelFractalPresenter\");\n```\n\n### Skip Presenter defined in the repository\n\nUse *skipPresenter* before any other chaining method\n\n```php\n$posts = $this->repository->skipPresenter()->all();\n```\n\nor\n\n```php\n$this->repository->skipPresenter();\n\n$posts = $this->repository->all();\n```\n","andersao\u002Fl5-repository 项目旨在为 Laravel 5 应用提供数据层抽象，通过引入仓库模式使应用的数据访问更加灵活和易于维护。其核心功能包括支持多种接口（如 RepositoryInterface、RepositoryCriteriaInterface 等），以及缓存管理和验证器集成，能够有效提升开发效率与代码质量。此外，该项目还提供了强大的生成器工具，帮助开发者快速构建模型、仓库等基础组件。适合于需要在 Laravel 框架下实现复杂业务逻辑或对数据库操作有较高定制需求的场景中使用。","2026-06-11 03:17:51","top_language"]