{"id":36374669,"url":"https://github.com/alcidesrh/laravel-generic-resource","last_synced_at":"2026-01-11T14:05:28.171Z","repository":{"id":56943962,"uuid":"352494579","full_name":"alcidesrh/laravel-generic-resource","owner":"alcidesrh","description":"A generic and agnostic Laravel Resource and ResourceCollection.","archived":false,"fork":false,"pushed_at":"2022-07-22T04:59:50.000Z","size":75,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-05-17T05:16:33.780Z","etag":null,"topics":["agnostic-implementation","api","collection","generic","resource"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/alcidesrh.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-03-29T02:37:47.000Z","updated_at":"2025-05-12T03:53:30.000Z","dependencies_parsed_at":"2022-08-21T07:50:43.510Z","dependency_job_id":null,"html_url":"https://github.com/alcidesrh/laravel-generic-resource","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/alcidesrh/laravel-generic-resource","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alcidesrh%2Flaravel-generic-resource","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alcidesrh%2Flaravel-generic-resource/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alcidesrh%2Flaravel-generic-resource/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alcidesrh%2Flaravel-generic-resource/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/alcidesrh","download_url":"https://codeload.github.com/alcidesrh/laravel-generic-resource/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alcidesrh%2Flaravel-generic-resource/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28306985,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-11T11:18:18.743Z","status":"ssl_error","status_checked_at":"2026-01-11T11:07:56.842Z","response_time":60,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agnostic-implementation","api","collection","generic","resource"],"created_at":"2026-01-11T14:05:26.757Z","updated_at":"2026-01-11T14:05:28.163Z","avatar_url":"https://github.com/alcidesrh.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"\n## A generic Laravel Resource and ResourceCollection\n\n\n**Basic use**\n\n```php\n  use Alcidesrh\\Generic\\GenericResource;\n\n  $user = User::find(1);\n\n  // It will only return the id and name fields.\n  return new GenericResource( $user, ['id', 'name']);\n```\n\nThis package can help you to return data as a traditional Laravel Resource without making a Resource or ResourceCollection for every single Model.\n\n\u003c!-- Sometimes you may need just the id and name fields of an entity: e.g. to list it in an input select.\n\nMaybe you can use an existing Resource of that entity, but if that Resource returns more that the id and name fields, then\nyou are doing data **overfetching** that can slow down the app and it could bring others issues like memory leaks for example.\n\nAnother solution is to make a dedicated Resource for that particular case, but as the app grows, you will find yourself making a new\nResource for every single case, even when you need to fetch some data that doesn't require a complex transformation. --\u003e\n\n\u003c!-- `GenericResource` and `GenericResourceColecction` implement a solution to deal with that.   --\u003e\n\u003cbr\u003e\n\n \u003cdetails open=\"open\"\u003e\n  \u003csummary\u003eTable of Contents\u003c/summary\u003e\n  \u003col\u003e\n    \u003cli\u003e\u003ca href=\"#requirements\"\u003eRequirements\u003c/a\u003e\u003c/li\u003e\n    \u003cli\u003e\u003ca href=\"#installation\"\u003eInstallation\u003c/a\u003e\u003c/li\u003e\n    \u003cli\u003e\n      \u003ca href=\"#usage\"\u003eUsage\u003c/a\u003e\n      \u003cul\u003e\n        \u003cli\u003e\u003ca href=\"#genericresource\"\u003eGenericResource\u003c/a\u003e\u003c/li\u003e\n        \u003cli\u003e\u003ca href=\"#genericresourcecollection\"\u003eGenericResourceCollection\u003c/a\u003e\u003c/li\u003e\n        \u003cli\u003e\u003ca href=\"#genericcontroller\"\u003eGenericController\u003c/a\u003e\n    \u003cul\u003e\n        \u003cli\u003e\u003ca href=\"#route-namespace-and-pagination-configuration\"\u003eRoute namespace and pagination configuration\u003c/a\u003e\u003c/li\u003e\n      \u003c/ul\u003e\n    \u003c/li\u003e\n      \u003c/ul\u003e\n    \u003c/li\u003e   \n  \u003c/ol\u003e\n\u003c/details\u003e\n\u003cbr\u003e\n\n## Requirements\n\n-Laravel \u003e= 5  \n-php \u003e= 7.0\n\n\u003cbr\u003e\n\n## Installation\n\n```sh\ncomposer require alcidesrh/laravel-generic-resource\n```\n\n\u003cbr\u003e\n\n**Working with nested or related models**\n\nSupose the User class has a parent property of type User class as well, a `belongsTo` relation with itself. And also has a `belongsToMany` relation with Product class. So `$user-\u003eparent` returns an intance of User class and `$user-\u003eproducts` a collection of intances of Product class.\n\nLet say we want a list of users with just these fields: id, name, parent (only the id and name fields of the parent) and products list (only the id, name and price fields of the product). This is how we can get only those data:\n\n```php\n  use Alcidesrh\\Generic\\GenericResource;\n\n  $user = User::find(1);\n  return new GenericResource( $user, [\n      'id',\n      'name',\n      'parent' =\u003e ['id', 'name'],\n      'products' =\u003e ['id', 'name', 'price']\n  ]);\n```\n\n\u003cbr\u003e\nYou can add many nested level as the relations allow:  \n\u003cbr\u003e\n\u003cbr\u003e\n\n```php\n    ...\n    'products' =\u003e [\n      'id',\n      'name',\n      'price',\n      'order' =\u003e [\n        'id',\n        'created_at',\n        'company' =\u003e [\n          'id',\n          'name'\n        ]\n      ]\n    ]\n```\n\n\u003cbr\u003e\n\n**Important:** In order to return nested relations data it is required make the query through the model's Facade.\n\n```php\n    // this will work\n    new GenericResource( User::find(1), ['id', 'name'] );\n\n    // this will work\n    new GenericResource( User::find(1), ['id', 'name', 'parent' =\u003e ['id', 'name']] );\n\n    // this will work\n    new GenericResource( DB::table('users')-\u003ewhere('id', 1)-\u003efirst(), ['id', 'name'] )\n\n    // this won't\n    new GenericResource( DB::table('users')-\u003ewhere('id', 1)-\u003efirst(), [\n        'id',\n        'name',\n        'parent' =\u003e ['id', 'name']\n        // it can not be access the parent property since the object retrieved is an stdClass type\n    ] );\n```\n\n  \u003cbr\u003e\n \n**Note:**  \n- If the second argument (the array of fields to get) is not supplied, all fields of the model will be returned.  \n- If one of the fields to return doesn't exist in the model, will be omitted in the result array.\n\n\u003cbr\u003e\n\n#### GenericResourceCollection\n\n```php\n   use Alcidesrh\\Generic\\GenericResourceCollection;\n\n   $users = User::where('active', 1);\n   // it will return a collection of user with only the id and name fields.\n   return new GenericResourceCollection( $users-\u003epaginate( $perPage ), ['id', 'name']);\n\n   //you can pass nested property as well as in the GenericResource\n   return new GenericResourceCollection( $users-\u003epaginate( $perPage ), [\n       'id',\n       'name',\n       'parent' =\u003e ['id', 'name'],\n       'products' =\u003e ['id', 'name', 'price']\n   ]);\n```\n\n\u003cbr\u003e\n\n**Note**: Both `GenericResource` and `GenericResourceCollection` classes were made following the guide line from the official [Laravel's Api Resources documentation](https://laravel.com/docs/8.x/eloquent-resources) with some extra code to make it generic. So you can expect the same structure and behavior.\n\n\u003cbr\u003e\n\n## GenericController\n\nThe main goal of this package is to provide `GenericResource` and `GenericResourceCollection`. However this package also provides a `GenericController` which can be used to fetch data that doesn't require a complex query or transformation, and it will return a `GenericResource` or `GenericResourceCollection` only with the fields that were requested or all fields if none was requested.\n\nIt can help to prevent overloading the app with routes and controller functions for every small and simple data portion required dynamically in the front-end via ajax.\n\nThe `GenericController` has five routes:\n\n```php\nMethod: POST /generic/list\nMethod: POST /generic/create\nMethod: POST /generic/update\nMethod: POST /generic/item\nMethod: POST /generic/delete\n```\n\n  \u003cbr\u003e\n\n### /generic/list get a list. It return a GenericResourceCollection\n\n```js\naxios.post(\"/generic/list\", {\n  // table to query\n  table: \"users\",\n  // page to return\n  page: 1,\n  // item per page\n  itemsPerPage: 10,\n  // fileds to return\n  fields: [\"id\", \"name\", \"created_at\", \"role_id\", \"email\", \"company_id\"],\n  // where clause: rule is column: value or column: {operator: someoperator, value: somevalue}\n  // operator value should be some of these: '=', '!=', '\u003c', '\u003c=', '\u003e', '\u003e=', '\u003c\u003e', 'like', 'contain'\n  where: {\n    // will generate ( created_at \u003e '2021-03-11 20:26:00.0' )\n    created_at: { operator: \"\u003e\", value: \"2020-09-11 20:26:00.0\" },\n    // will generate ( email_verified_at IS NOT NULL )\n    email_verified_at: { operator: \"!=\", value: null },\n    // when the operator's parameter is omitted the default operator will be '=', will generate ( role_id = 2 )\n    role_id: 2,\n    // the non-existent 'contain' will generate ( email LIKE %legendary% AND email LIKE %zangetsu% )\n    // this example zangetsu.ins@company.com and jhon.legendary.dc@company.com will match\n    email: { operator: \"contain\", value: [\"legendary\", \"zangetsu\"] },\n  },\n  //orWhere clause accept same rules as simple where with one more\n  orWhere: {\n    // you can pass an array as a value, it will generate (role_id = 1 OR role_id = 2)\n    role_id: [1, 2],\n    // will generate (role_id != 1 OR role_id != 2)\n    role_id: { operator: \"!=\", value: [1, 2] },\n  },\n  whereIn: {\n    // return items with those ids\n    id: [1, 23, 35],\n  },\n  whereNotIn: {\n    // return items with neither of these ids\n    id: [1, 23, 35],\n  },\n  whereBetween: {\n    // return items with price between 25 and 35\n    price: [25, 35],\n  },\n  // return items with price less than 25 and greater than 35\n  whereNotBetween: {\n    id: [25, 35],\n  },\n  // order by id ascendingly of course the value can be DESC\n  orderBy: {\n    id: \"ASC\",\n  },\n});\n```\n\n\u003cbr\u003e\n\n**Note:** It is not posible to ask for nested relations data in the `fields` parameter above due the generic nature of the query. DB Facade is used to make the query, which returns stdClass type.\n\n\u003cbr\u003e\n\n### /generic/create create an item. It will return a GenericResource\n\n```js\naxios.post(\"/generic/create\", {\n  table: \"roles\",\n  // fields to return in the GenericResource once created\n  fields: [\"id\", \"name\"],\n  // values: pair column: value\n  values: {\n    name: \"Admin\",\n    slug: \"admin\",\n  },\n  // can insert many in one request\n  many: [\n    {\n      name: \"User editor\",\n      slug: \"user-editor\",\n    },\n    {\n      name: \"Forum admin\",\n      slug: \"forum-admin\",\n    },\n  ],\n});\n```\n\n  \u003cbr\u003e\n  \n  ### /generic/update update an item. It will return a GenericResource\n\n```js\naxios\n.post(\"/generic/update\", {\n  table: \"roles\",\n  // id of the item to update\n  id: 3,\n  // many ids to update many items with the same values in one request.\n  many: [35, 36, 37]\n  // fields to return in the GenericResource once updated\n  fields: [\"id\", \"name\"],\n  // values: pair column: value\n  values: {\n    name: \"Room Admin\",\n    slug: \"room-admin\",\n  },\n});\n```\n\n  \u003cbr\u003e\n  \n  ### /generic/item to get an item. It will return a GenericResource\n\n```js\naxios.post(\"/generic/delete\", {\n  table: \"user\",\n  // id of the item to delete\n  id: 3,\n  //fields to return in the GenericResource\n  fields: [\"id\", \"name\", \"slug\"],\n});\n```\n\n  \u003cbr\u003e\n  \n  ### /generic/delete delete an item  \n  \n  ```js\n  axios\n  .post(\"/generic/delete\", {\n    table: \"user\",\n    // id of the item to delete\n    id: 3,\n  });\n  ```\n\n  \u003cbr\u003e\n\n## Route namespace and pagination configuration\n\nOnce installed runing console command ` php artisan vendor:publish` will publish the package's configuration. It can also be done manually copy /vendor/alcidesrh/generic-resource.php to /config  \n\u003cbr\u003e\n\n**/config/generic-resource.php**\n\n```php\n\nreturn [\n\n    /*\n    |--------------------------------------------------------------------------\n    | Laravel generic Resource package configuration\n    |--------------------------------------------------------------------------\n    |\n     */\n    // configure route and prefix\n    // e.g. to have this route https://yourdomain/products/items for items list\n    // change 'prefix' key value to 'products' and 'list_route_name' key value to 'items'\n    'route' =\u003e [\n\n        //Route's prefix for generic CRUD(create, read, update and delete) operations\n        //Deafault 'generic' e.g.: axios.post( 'https://yourdomain/generic' )\n        'prefix' =\u003e 'generic',\n\n        //Route for list of generic items.\n        //Deafault 'list' e.g. axios.post( 'https://yourdomain/generic/list' )\n        'list_route_name' =\u003e 'list',\n\n        //Route to create an item.\n        //Deafault 'create' e.g. axios.post( 'https://yourdomain/generic/create', {table: 'users', values: [ {username: 'whatever', role_id: 1}], field: [id, username] } )\n        'create_route_name' =\u003e 'create',\n\n        //Route to update an item.\n        //Deafault 'update'  e.g. axios.post( 'https://yourdomain/generic/update', {table: 'users', id: 1, values: [ {username: 'whatever', role_id: 1}], field: [id, username] } )\n        'update_route_name' =\u003e 'update',\n\n        //Route to get an item.\n        //Deafault 'item' e.g. axios.post( 'https://yourdomain/generic/item', {table: 'users', fields: [ {username: 'whatever', role_id: 1}] } )\n        'show_route_name' =\u003e 'item',\n\n        //Route to delete a generic item.\n        //Deafault 'delete' e.g. axios.post( 'https://yourdomain/generic/delete', {table: 'users', id: 1} )\n        'delete_route_name' =\u003e 'delete',\n    ],\n    // configure pagination items per page and parameters names.\n    'pagination' =\u003e [\n\n        //Items per page. Default 20.\n        'itemsPerPage' =\u003e 20,\n\n        //Name of the param of the current page e.g. axios.post( 'https://yourdomain/generic/delete', {table: 'users', page: 1} )\n        'name_param_page' =\u003e 'page',\n\n        //Name of the param of the number of items per page e.g. axios.post( 'https://yourdomain/generic/list', {table: 'users', page: 1, itemsPerPage: 30} )\n        'name_param_item_per_page' =\u003e 'itemsPerPage',\n    ],\n];\n```\n\n\u003cbr\u003e\n\n_If you find this package useful please consider star it. Thank you._\n\n### License\n\nThis Generic Resource package for Laravel is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falcidesrh%2Flaravel-generic-resource","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falcidesrh%2Flaravel-generic-resource","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falcidesrh%2Flaravel-generic-resource/lists"}