-
-
Notifications
You must be signed in to change notification settings - Fork 18
Building a Basic Api Tutorial Part 4 Resources
Making use of Collections / Resources we can next manipulate our response: https://laravel.com/docs/6.x/eloquent-resources
Lets setup one for our User Model:
-
php artisan make:resource UserResource
andphp artisan make:resource UserCollection
to generate our resource and collection. At the top of the controller:
/**
* Resource for item.
*
* @var mixed instance of \Illuminate\Http\Resources\Json\JsonResource
*/
protected $resourceSingle = UserResource::class;
/**
* Resource for collection.
*
* @var mixed instance of \Illuminate\Http\Resources\Json\ResourceCollection
*/
protected $resourceCollection = UserCollection::class;
Next lets setup these resources to extend our ApiResources: Open the UserResource and change the definition to
use Phpsa\LaravelApiController\Http\Resources\ApiResource;
class UserResource extends ApiResource
and the UserCollection change definition to
use Phpsa\LaravelApiController\Http\Resources\ApiResource;
class UserCollection extends ApiResource
Now for some of the magic.
- Lets standardize our response Case : currently getting a user responds with:
{
"data": {
"id": 1,
"name": "cdadmin",
"email": "[email protected]",
"email_verified_at": null,
"created_at": null,
"updated_at": null
}
}
Now in your request add the following header:
X-Accept-Case-Type: camel
(or camel-case) and your response should now:
{
"data": {
"id": 1,
"name": "cdadmin",
"email": "[email protected]",
"emailVerifiedAt": null,
"createdAt": null,
"updatedAt": null
}
}
Using snake / snake-case will make sure all are snake cased.
-- Optionally -- api headers middleware ? 5. Seed admin User 6. Oauth + Secrets 7. Setup in postman (optionally extra postman package to get initial api points) 8. Install api-controller package.
---- End Part 1
--- start Part 2
-
- setup Users Endpoint to map to users model
-
- add Policy for security
-
- Add Resource for response
-
- Add Request for Validation
-
- Add Scope for extra scope
- by this point should have a basic CRUD group.
- -- Custom Endpoint -- Me - for own profile
--- end Part 2
--- start part 3 (advanced extras)
- -- joins