{"id":15067026,"url":"https://github.com/cba85/laravel5-7-api-resources","last_synced_at":"2025-10-05T04:31:35.574Z","repository":{"id":71449335,"uuid":"239360671","full_name":"cba85/laravel5-7-api-resources","owner":"cba85","description":"Laravel API Ressources","archived":true,"fork":false,"pushed_at":"2020-02-09T19:24:26.000Z","size":255,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2024-09-29T11:40:41.036Z","etag":null,"topics":["api-resources","laravel7"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":false,"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/cba85.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,"governance":null}},"created_at":"2020-02-09T19:23:31.000Z","updated_at":"2023-04-23T15:07:18.000Z","dependencies_parsed_at":"2023-08-01T22:57:16.904Z","dependency_job_id":null,"html_url":"https://github.com/cba85/laravel5-7-api-resources","commit_stats":null,"previous_names":["cba85/laravel5-7-api-resources"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cba85%2Flaravel5-7-api-resources","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cba85%2Flaravel5-7-api-resources/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cba85%2Flaravel5-7-api-resources/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cba85%2Flaravel5-7-api-resources/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cba85","download_url":"https://codeload.github.com/cba85/laravel5-7-api-resources/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":235364840,"owners_count":18978248,"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-resources","laravel7"],"created_at":"2024-09-25T01:15:19.594Z","updated_at":"2025-10-05T04:31:28.234Z","avatar_url":"https://github.com/cba85.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# API Resources\n\n## Basic\n\n1. Install authentification\n    ```bash\n    $ php artisan make:auth\n    $ php artisan migrate\n    ```\n\n    - Restart `php artisan serve`\n\n    - In database/seed/DatabaseSeeder.php:\n\n        https://laravel.com/docs/5.7/seeding\n\n        ```php\n        DB::table('users')-\u003einsert([\n                'name' =\u003e str_random(10),\n                'email' =\u003e str_random(10).'@gmail.com',\n                'password' =\u003e bcrypt('secret'),\n            ]);\n        ```\n\n2. Create a route\n\n    - In routes/web.php:\n\n        ```php\n        Route::get('/user/{user}', function (\\App\\User $user) {\n            return $user;\n        });\n        ```\n\n    - In app/User.php:\n\n        ```php\n        protected $appends = ['humanCreatedAt'];\n\n        public function getHumanCreatedAtAttribute()\n        {\n            return $this-\u003ecreated_at-\u003ediffForHumans();\n        }\n        ```\n\n3. Create a resource\n\n    ```bash\n    $ php artisan make:resource UserResource\n    ```\n\n    - In routes/web.php:\n\n    ```php\n    Route::get('/user/{user}', function (\\App\\User $user) {\n        return new \\App\\Http\\Resources\\UserResource($user);\n    });\n    ```\n\n    - In app/Http/Resources/UserResource.php:\n\n        ```php\n        public function toArray($request)\n        {\n            //return parent::toArray($request);\n            return [\n                'id' =\u003e $this-\u003eid,\n                'email' =\u003e $this-\u003eemail\n            ];\n        }\n        ```\n\n## Static collection method\n\n1. Create model and factory\n\n```bash\n$ php artisan make:model Topic -mf\n```\n\n2. Create table in database\n\n    - In database/migrations:\n\n        ```php\n        public function up()\n        {\n            Schema::create('topics', function (Blueprint $table) {\n                $table-\u003eincrements('id');\n                $table-\u003einteger('user_id');\n                $table-\u003estring('title');\n                $table-\u003etimestamps();\n            });\n        }\n        ```\n\n        ```bash\n        $ php artisan migrate\n        ```\n\n    - [WORK] In database/seeders/DatabaseSeeder.php:\n\n        ```php\n        foreach(range(1, 10) as $i) {\n            $topic-\u003ecreate([\n                'title' =\u003e $faker-\u003esentence(),\n                'user_id' =\u003e 1\n            ]);\n        }\n        foreach(range(1, 10) as $i) {\n            $topic-\u003ecreate([\n                'title' =\u003e $faker-\u003esentence(),\n                'user_id' =\u003e 2\n            ]);\n        }\n        ```\n\n    - [DOESN'T WORK] In database/factories/TopicFactory.php:\n\n        ```php\n        $factory-\u003edefine(\\App\\Topic::class, function (Faker $faker) {\n            return [\n                'title' =\u003e $faker-\u003esentence,\n                'user_id' =\u003e 1,\n            ];\n        });\n        ```\n\n        ```bash\n        $ php artisan tinker\n        factory(\\App\\Topic::class, 10)-\u003ecreate()\n        ```\n\n3. Create resource\n\n    - In routes/web.php:\n\n        ```php\n        Route::get('/topics', function () {\n            return new \\App\\Http\\Resources\\TopicResource(\\App\\Topic::get());\n        });\n        ```\n\n        ```bash\n        $ php artisan make:resource TopicResource\n        ```\n\n    - In app/Http/Resources/TopicResource.php:\n\n        ```php\n        public function toArray($request)\n        {\n            return [\n                'id' =\u003e $this-\u003eid,\n                'title' =\u003e $this-\u003etitle\n            ];\n        }\n        ```\n\n        ```php\n        public function toArray($request) {\n            dd($this-\u003ecollection);\n            dd($this-\u003eresource);\n        ...\n        }\n        ```\n\n    - In routes/web.php:\n\n        ```php\n        Route::get('/topics', function () {\n            return \\App\\Http\\Resources\\TopicResource::collection(\\App\\Topic::get());\n        });\n        ```\n\n## Resource collections\n\n1. Create collection\n\n    ```bash\n    $ php artisan make:resource TopicCollection\n    # or\n    $ php artisan make:resource TopicResourceC --collection\n    ```\n\n2. Modify collection\n\n    - In App/Http/Resources/TopicCollection.php:\n\n        ```php\n        public function toArray($request)\n        {\n            return [\n                'id' =\u003e $this-\u003eid,\n                'title' =\u003e $this-\u003etitle\n            ];\n        }\n        ```\n\n    - In routes/web.php:\n\n        ```php\n        Route::get('/topics', function () {\n            return new \\App\\Http\\Resources\\TopicCollection(\\App\\Topic::get());\n        });\n        ```\n\n    - In App/Http/Resources/TopicCollection.php:\n\n        ```php\n        public function toArray($request)\n        {\n            //dd($this-\u003ecollection);\n            return [\n                'data' =\u003e $this-\u003ecollection,\n                'meta' =\u003e [\n                    'total' =\u003e $this-\u003ecollection-\u003ecount()\n                ]\n            ];\n        }\n        ```\n\n        ```php\n        public function toArray($request)\n            {\n            return [\n                    'data' =\u003e TopicResource::collection($this-\u003ecollection),\n                    'meta' =\u003e [\n                        'total' =\u003e $this-\u003ecollection-\u003ecount()\n                    ]\n                ];\n        }\n        ```\n\n## Another way to add meta\n\n- In routes/web.php:\n\n    ```php\n    Route::get('/u', function () {\n        return new \\App\\Http\\Resources\\UserResource(\\App\\User::find(1));\n    });\n    ```\n\n    ```php\n    Route::get('/u', function () {\n        return (new \\App\\Http\\Resources\\UserResource(\\App\\User::find(1)))-\u003eadditional([\n            'meta' =\u003e [\n                'token' =\u003e '123456789'\n            ]\n        ]);\n    });\n    ```\n\n## Pagination\n\n- In routes/web.php:\n\n    ```php\n    Route::get('/topics', function () {\n        return \\App\\Http\\Resources\\TopicResource::collection(\\App\\Topic::paginate(3));\n    });\n    ```\n\n    ```php\n        Route::get('/topics', function () {\n        return new \\App\\Http\\Resources\\TopicCollection(\\App\\Topic::paginate(3));\n    });\n    ```\n\n## Relationships\n\n- Create a new Model:\n\n    ```bash\n    $ php artisan make:model Post -mf\n    ```\n\n- Migration in database/migrations:\n\n    ```php\n    Schema::create('posts', function (Blueprint $table) {\n        $table-\u003eincrements('id');\n        $table-\u003einteger('user_id');\n        $table-\u003einteger('topic_id');\n        $table-\u003etext('body');\n        $table-\u003etimestamps();\n    });\n    ```\n\n    ```bash\n    $ php artisan migrate\n    ```\n\n- Seed database:\n\n    - In database/seeds/DatabaseSeeder.php:\n\n        ```php\n        foreach(range(1, 10) as $i) {\n            $post-\u003ecreate([\n                'topic_id' =\u003e 1,\n                'body' =\u003e $faker-\u003esentence(),\n                'user_id' =\u003e 1\n            ]);\n        }\n        ```\n\n    - In routes/web.php:\n\n        ```php\n        Route::get('/topics', function () {\n            return new \\App\\Http\\Resources\\TopicCollection(\\App\\Topic::get());\n        });\n        ```\n\n    - In App/Http/Resources/TopicResource:\n\n        ```php\n        public function toArray($request)\n        {\n            return [\n                'id' =\u003e $this-\u003eid,\n                'title' =\u003e $this-\u003etitle,\n                'posts' =\u003e $this-\u003eposts,\n            ];\n        }\n        ```\n\n    - Create a Post resource:\n\n        ```bash\n        $ php artisan make:resource PostResource\n        ```\n\n    - In App/Http/Resources/TopicResource.php:\n\n        ```php\n        public function toArray($request)\n        {\n            return [\n                'id' =\u003e $this-\u003eid,\n                'title' =\u003e $this-\u003etitle,\n                'posts' =\u003e PostResource::collection($this-\u003eposts),\n            ];\n        }\n        ```\n\n    - In App\\Http\\Resource\\PostResource.php:\n\n        ```php\n        public function toArray($request)\n        {\n            return [\n                'id' =\u003e $this-\u003eid,\n                'body' =\u003e $this-\u003ebody,\n                'user' =\u003e new UserResource($this-\u003euser)\n            ];\n        }\n        ```\n\n    - In App\\Post.php:\n\n        ```php\n        public function user()\n        {\n            return $this-\u003ebelongsTo(User::class);\n        }\n        ```\n\n    - In App/Http/Resources/TopicResource.php:\n\n        ```php\n        public function toArray($request)\n        {\n            return [\n                'id' =\u003e $this-\u003eid,\n                'title' =\u003e $this-\u003etitle,\n                'posts' =\u003e PostResource::collection($this-\u003eposts),\n                'user' =\u003e new UserResource($this-\u003euser)\n            ];\n        }\n        ```\n\n    - In App\\Topic.php:\n\n        ```php\n        public function user()\n        {\n            return $this-\u003ebelongsTo(User::class);\n        }\n        ```\n\n## N+1 problem\n\n- In routes/web.php:\n\n    ```php\n    DB::listen(function ($query) {\n        dump($query-\u003esql);\n    });\n    ```\n\n    ```php\n    Route::get('/topics', function () {\n        return new \\App\\Http\\Resources\\TopicCollection(\\App\\Topic::with(['user', 'posts'])-\u003eget());\n    });\n    ```\n\n## Conditionals\n\n- In App/Http/Resources/TopicRessource.php:\n\n    ```php\n    public function toArray($request)\n    {\n        return [\n            'id' =\u003e $this-\u003eid,\n            'title' =\u003e $this-\u003etitle,\n            'posts' =\u003e PostResource::collection($this-\u003ewhenLoaded('posts')),\n            'user' =\u003e new UserResource($this-\u003euser)\n        ];\n    }\n    ```\n\n- In routes/web.php:\n\n    ```php\n    return new \\App\\Http\\Resources\\TopicCollection(\\App\\Topic::with(['user'])-\u003eget());\n    ```\n\n- In App/Http/Resources/TopicRessource.php:\n\n    ```php\n    public function toArray($request)\n    {\n        $return [\n            'id' =\u003e $this-\u003eid,\n            'secret' =\u003e 'abc',\n            'title' =\u003e $this-\u003etitle,\n            'posts' =\u003e PostResource::collection($this-\u003ewhenLoaded('posts')),\n            'user' =\u003e new UserResource($this-\u003euser)\n        ];\n    }\n    ```\n\n    ```php\n    public function toArray($request)\n    {\n        $data = [\n            'id' =\u003e $this-\u003eid,\n            'secret' =\u003e 'abc',\n            'title' =\u003e $this-\u003etitle,\n            'posts' =\u003e PostResource::collection($this-\u003ewhenLoaded('posts')),\n            'user' =\u003e new UserResource($this-\u003euser)\n        ];\n\n        if ($this-\u003euser_id == 1) {\n            $data['secret'] = 'abc';\n        }\n\n        return $data;\n    }\n    ```\n\n    ```php\n    public function toArray($request)\n    {\n        return [\n            'id' =\u003e $this-\u003eid,\n            'secret' =\u003e $this-\u003ewhen($this-\u003euser_id == 1, ['abc']),\n            'title' =\u003e $this-\u003etitle,\n            'posts' =\u003e PostResource::collection($this-\u003ewhenLoaded('posts')),\n            'user' =\u003e new UserResource($this-\u003euser)\n        ];\n    }\n    ```\n\n    ```php\n    public function toArray($request)\n    {\n        return [\n            'id' =\u003e $this-\u003eid,\n            $this-\u003emergeWhen($this-\u003euser_id == 1, [\n                'secret' =\u003e 'abc'\n            ]),\n            'title' =\u003e $this-\u003etitle,\n            'posts' =\u003e PostResource::collection($this-\u003ewhenLoaded('posts')),\n            'user' =\u003e new UserResource($this-\u003euser)\n        ];\n    }\n    ```\n\n## Unit tests\n\n- Create unit test:\n\n    ```bash\n    $ php artisan make:test TopicResourceTest --unit\n    ```\n\n- In tests/Unit/TopicResource.php:\n\n    ```php\n    public function testReturnsCorrectData()\n    {\n        $resource = new \\App\\Http\\Resources\\TopicResource($topic = factory(\\App\\Topic::class)-\u003ecreate());\n        dd($resource);\n    }\n    ```\n\n    ```php\n    public function testReturnsCorrectData()\n    {/\n        $resource = (new \\App\\Http\\Resources\\TopicResource($topic = factory(\\App\\Topic::class)-\u003ecreate()))-\u003ejsonSerialize();\n        dd($resource);\n    }\n    ```\n\n    ```php\n    public function testReturnsCorrectData()\n    {\n        $resource = (new \\App\\Http\\Resources\\TopicResource($topic = factory(\\App\\Topic::class)-\u003ecreate()))-\u003ejsonSerialize();\n        $this-\u003eassertArraySubset([\n            'id' =\u003e $topic-\u003eid,\n            'title' =\u003e $topic-\u003etitle\n        ], $resource);\n    }\n    ```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcba85%2Flaravel5-7-api-resources","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcba85%2Flaravel5-7-api-resources","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcba85%2Flaravel5-7-api-resources/lists"}