{"id":18654681,"url":"https://github.com/juampi92/api-resources","last_synced_at":"2025-10-18T05:57:55.471Z","repository":{"id":29490606,"uuid":"121772324","full_name":"juampi92/api-resources","owner":"juampi92","description":"Manage your Laravel Eloquent Resources maintaining API versioning","archived":false,"fork":false,"pushed_at":"2024-03-02T07:57:19.000Z","size":57,"stargazers_count":111,"open_issues_count":2,"forks_count":18,"subscribers_count":7,"default_branch":"master","last_synced_at":"2024-03-15T12:12:40.155Z","etag":null,"topics":["api","laravel","php"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/juampi92.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":".github/CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":".github/SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"Juampi92"}},"created_at":"2018-02-16T16:21:39.000Z","updated_at":"2024-06-19T04:11:08.372Z","dependencies_parsed_at":"2024-06-19T04:11:06.983Z","dependency_job_id":"63fe31b3-6cee-4f95-b953-bc5008d13ba8","html_url":"https://github.com/juampi92/api-resources","commit_stats":{"total_commits":29,"total_committers":4,"mean_commits":7.25,"dds":"0.31034482758620685","last_synced_commit":"11f60a76392af8f8891ba5878e35430195d3b135"},"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/juampi92%2Fapi-resources","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/juampi92%2Fapi-resources/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/juampi92%2Fapi-resources/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/juampi92%2Fapi-resources/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/juampi92","download_url":"https://codeload.github.com/juampi92/api-resources/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247299831,"owners_count":20916190,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":["api","laravel","php"],"created_at":"2024-11-07T07:16:12.407Z","updated_at":"2025-10-18T05:57:50.417Z","avatar_url":"https://github.com/juampi92.png","language":"PHP","readme":"# Api Resources\n[![Latest Version](https://img.shields.io/github/release/juampi92/api-resources.svg?style=flat-square)](https://github.com/juampi92/api-resources/releases)\n[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/juampi92/api-resources/run-tests.yml?branch=master\u0026label=Tests\u0026style=flat-square)](https://github.com/juampi92/api-resources/actions?query=workflow%3ATests+branch%3Amaster)\n[![Total Downloads](https://img.shields.io/packagist/dt/juampi92/api-resources.svg?style=flat-square)](https://packagist.org/packages/juampi92/api-resources)\n[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md)\n\nManage your resources maintaining API versioning. With a simple middleware separate routes by api version, and smart instanciate [Http\\Resources](https://laravel.com/docs/5.5/eloquent-resources) based on this version.\n\nAdd the middleware `'api.v:2'` on your api/v2 group.\n\nAnd then `api_resource('App\\User')-\u003emake($user)` is the same as `new App\\Http\\Resources\\App\\v2\\User($user)`, but version free.\n\n```bash\nApp\\Http\\Resources\\\n  |- App\\\n    |- v1\\\n      |- User.php\n    |- v2\\\n      |- Rank.php\n      |- User.php\n```\n\n### The idea behing this\n\nA while back I faced this API versioning problem, so I wrote this [medium post](https://medium.com/@juampi92/api-versioning-using-laravels-resources-b1687a6d2c22) with my solution and this package reflects this.\n\n## Installation\n\nYou can install this package via composer using:\n\n```bash\ncomposer require juampi92/api-resources\n```\n\nThe package will automatically register itself.\n\n### Config\n\nTo publish the config file to `config/api.php` run:\n\n```bash\nphp artisan vendor:publish --provider=\"Juampi92\\APIResources\\APIResourcesServiceProvider\"\n```\n\nThis will publish a file `api.php` in your config directory with the following content:\n```php\nreturn [\n  /*\n  |--------------------------------------------------------------------------\n  | API Version\n  |--------------------------------------------------------------------------\n  |\n  | This value is the latest version of your api. This is used when\n  | there's no specified version on the routes, so it will take this as the\n  | default, or latest.\n   */\n   'version' =\u003e '1',\n\n   /*\n   |--------------------------------------------------------------------------\n   | Resources home path\n   |--------------------------------------------------------------------------\n   |\n   | This value is the base folder where your resources are stored.\n   | When using multiple APIs, you can leave it as a string if every\n   | api is in the same folder, or as an array with the APIs as keys.\n    */\n    'resources_path' =\u003e 'App\\Http\\Resources',\n    \n    /*\n    |--------------------------------------------------------------------------\n    | Resources\n    |--------------------------------------------------------------------------\n    |\n    | Here is the folder that has versioned resources. If you store them\n    | in the root of 'resources_path', leave this empty or null.\n     */\n    'resources' =\u003e 'App'\n ];\n```\n\n### Middleware\n\nInstall this middleware on your `Http/Kernel.php` under the `$routeMiddleware`\n\n```php\n  protected $routeMiddleware = [\n    ...\n    'api.v'           =\u003e \\Juampi92\\APIResources\\Middleware\\APIversion::class,\n    ...\n  ];\n```\n\n## Configure correctly\n\nFor this package to work, you need to understand how it requires resources.\n\nIf we have the following config:\n```php\n[\n  'version' =\u003e '2',\n  'resources_path' =\u003e 'App\\Http\\Resources',\n  'resources' =\u003e 'Api'\n]\n```\n\nThis means that if you include the `Api\\User` resource, it will instantiate `App\\Http\\Resources\\Api\\v2\\User`.\n\n`Api` works for sub organizing your structure, but you can put your Resources versionate folders in the root, like this:\n\n```php\n[\n  'version' =\u003e '2',\n  'resources_path' =\u003e 'App\\Http\\Resources',\n  'resources' =\u003e ''\n]\n```\n\nNow if we include `User`, it will instantiate `App\\Http\\Resources\\v2\\User`.\n\n### Fallback\n\nWhen you use a version that is **NOT** the latest, if you try to include a Resource that's **NOT** defined inside that version's directory, this will automatically fallback in the **LATEST** version.\n\nThis way you don't have to duplicate new resources on previous versions.\n\n## Usage\n\n### Middleware\n\nWhen you group your API routes, you should now apply the middleware `api.v` into the group like this:\n\n```php\n// App v1 API\nRoute::group([\n    'middleware' =\u003e ['app', 'api.v:1'],\n    'prefix'     =\u003e 'api/v1',\n], function ($router) {\n    require base_path('routes/app_api.v1.php');\n});\n\n// App v2 API\nRoute::group([\n    'middleware' =\u003e ['app', 'api.v:2'],\n    'prefix'     =\u003e 'api/v2',\n], function ($router) {\n    require base_path('routes/app_api.v2.php');\n});\n```\n\nThat way, if you use the Facade, you can check the current version by doing `APIResource::getVersion()` and will return the version specified on the middleware.\n\n\n### Facade\n\nThere are many ways to create resources. You can use the Facade accessor:\n\n```php\nuse Juampi92\\APIResources\\Facades\\APIResource;\n\nclass SomethingController extends Controller {\n    ...\n\n    public function show(Something $model)\n    {\n      return APIResource::resolve('App\\Something')-\u003emake($model);\n    }\n}\n```\n\n### Global helper\n\n```php\nclass SomethingController extends Controller {\n    ...\n\n    public function show(Something $model)\n    {\n      return api_resource('App\\Something')-\u003emake($model);\n    }\n}\n```\n\n### Collections\n\nInstead of `make`, use `collection` for arrays, just like Laravel's documentation.\n\n```php\nclass SomethingController extends Controller {\n    ...\n\n    public function index()\n    {\n      $models = Something::all();\n      return api_resource('App\\Something')-\u003ecollection($models);\n    }\n}\n```\n\nIf you wanna use a ResourceCollection, you might wanna rewrite the `collects()` method.\n\n```php\nclass UserCollection extends ResourceCollection\n{\n    protected function collects()\n    {\n        return APIResource::resolveClassname('App\\User');\n    }\n}\n```\n\nThis way, the ResourceCollection will always have the correct class. \n\n`resolveClassname` will try to use the current version of the class, but if it's not possible, will use the latest.\n\n## Nested resources\n\nTo take advantage of the **fallback** functionality, it's recomended to use `api_resource` inside the resources. This way you preserve the right version, or the latest if it's not defined.\n\n```php\nclass Post extends Resource {\n    public function toArray($request)\n    {\n      return [\n        'title' =\u003e $this-\u003etitle,\n          ...\n        'user' =\u003e api_resource('App\\User')-\u003emake($this-\u003euser);\n      ];\n    }\n}\n```\n\n## Multiple APIs\n\nThere might be the case where you have more than one API living on the same project, but using diferent versions. This app supports that.\nFirst, the `config/api.php`\n\n```php\nreturn [\n  'default' =\u003e 'api',\n  'version' =\u003e [\n    'api'     =\u003e '2',\n    'desktop' =\u003e '3'\n  ],\n  'resources_path' =\u003e 'App\\Http\\Resources'\n  // Or one path each\n  'resources_path' =\u003e [\n    'api'     =\u003e 'App\\Http\\Resources',\n    'desktop' =\u003e 'Vendorname\\ExternalPackage\\Resources'\n  ],\n  'resources' =\u003e [\n    'api'     =\u003e 'Api',\n    'desktop' =\u003e ''\n  ],\n];\n```\n\nThen, you need to configure the **middleware**. Instead of using `api.v:1`, you now have to specify the name: `api.v:3,desktop`.\n\nThen the rest works as explained before.\n\n\n## API Route\n\nSometimes you must return a route url on the api response.\nIf you wanna keep the api version (which is always the current version), api-resources has the solution for you.\n\n```php\n// When defining the routes\nRoute::group([\n    'middleware' =\u003e ['app', 'api.v:1'],\n    'prefix'     =\u003e 'api/v1',\n    // Using name on a group will prefix it.\n    'name'       =\u003e 'api.v1.',\n], function ($router) {\n    Route::get('/auth/login', [\n        // This will be api.v1.auth.login\n        'name' =\u003e 'auth.login',\n        'use' =\u003e '...',\n    ]);\n});\n```\n\nWith this we have `api.v1.auth.login` and `api.v2.auth.login` when creating a new version.\n\nNow just do `api_route('api.auth.login')`, and it will output `/api/v1/auth/login` or `/api/v2/auth/login` accordingly.\n\n### How it works\n\nIt's grabbing the config `api.resources` and doing a strtolower, so if you have `'resources' =\u003e 'App'`, will transform `app.auth.login` into `app.v1.auth.login`.\nIf you need to customize it, add a new config entry in `config/api.php` like this:\n\n```php\n    /*\n    |--------------------------------------------------------------------------\n    | Route prefix\n    |--------------------------------------------------------------------------\n    |\n    | By default, the route prefix is the lowercase resources folder.\n    | So it'd be `app.v1.auth.login` has the prefix `app`.\n    |\n    | Using `app` will do api_route(`app.auth.login`) =\u003e `app.v?.auth.login`.\n    |\n     */\n\n    'route_prefix' =\u003e 'app'\n```\n\nIf works with multiple APIs as explained before.\n\n## Testing\n\nRun the tests with:\n```bash\nvendor/bin/phpunit\n```\n\n## Credits\n\n- [Juan Pablo Barreto](https://github.com/juampi92)\n- [All Contributors](../../contributors)\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","funding_links":["https://github.com/sponsors/Juampi92"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjuampi92%2Fapi-resources","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjuampi92%2Fapi-resources","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjuampi92%2Fapi-resources/lists"}