Skip to content

Getting Started

Max edited this page Apr 1, 2019 · 3 revisions

Route, Controller and Model.

There should be one model per API resource, and generally one controller per resource (at least in the most cases) and a set of routes to go with that controller.

You can create all of these things (and more!) with one simple command. If we wanted to make a new "book" resource for example, we would run;

./artisan make:api-resource Book

You will find this creates a lot of useful things, including:

  • Model, Controller
  • Migration, Seed
  • Policy

It is up to you to then define the specifics. For the simplest cases, you don't even need to edit the controller, just specify the details of your model (in particular the fillables and validation rules), and then specify the schema in your new migration.

Then once you add routes to your routes/api.php - you're good to go!

Validation

All relevant boilerplate code will use two functions to grab a list of rules, against which an API resource should be checked during creation and modification. These are just normal laravel validation rules. Both functions reside as methods within your model representing the relevant API resource.

getValidationRules()

This is the list of rules to be checked when a model is being created.

getValidationRulesUpdating()

This is the list of rules to be checked when a model is being updated. If left blank (as is by default), the rules for model creation are used. If you wish to remove a rule for a field (as relative to the rules for creating), just specify it and leave it's contents blank.

getValidationMessages()

This function can be used to return any custom validation messages. It works based on field names just like validation rules themselves.

Transformation

Transformation is a very important aspect of building APIs. The builderplate comes with a very powerful transformer, capable of transforming any levels of nested resources within your response and formatting the key case to anything you like on the fly (even letting the client pick!).

Generally when defining a custom transformer, you will want to begin by extending the existing one, and applying your own custom logic before or after the default transformation process. You can define a custom transformer for a model, or for a controller. The reasons you might want to favour one over the other, relate to where else these transformers are used. Keep in mind that model transformers are always preferred, and always used, regardless of which response of which request happens to contain that model somewhere nested in it's data.

For every given response, there is a hierarchy of transformers that are considered;

  • BaseTransformer - Used by default
  • Model Transformer - Used if defined on the model class, regardless of where this model is being transformed
  • Controller Transformer - Used for any responses from that controller