Skip to content

Building a Basic Api Tutorial Part 4 Resources

Craig Smith edited this page Dec 19, 2019 · 3 revisions

Data display on Return:

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 and php 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.

  1. 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
  1. by this point should have a basic CRUD group.
  2. -- Custom Endpoint -- Me - for own profile

--- end Part 2

--- start part 3 (advanced extras)

  1. -- joins
Clone this wiki locally