diff --git a/laravel/index.md b/laravel/index.md index 5b93da39d2f..07d504c05bf 100644 --- a/laravel/index.md +++ b/laravel/index.md @@ -165,9 +165,116 @@ So, if you want to access the raw data, you have two alternatives: For instance, go to `http://127.0.0.1:8000/api/books.jsonld` to retrieve the list of `Book` resources in JSON-LD. +> [!NOTE] +> Documentation for Eloquent "API resources" encourages using the JSON:API community format. +> While we recommend preferring JSON-LD when possible, JSON:API is also supported by API Platform, +> read the [Content Negotiation](#content-negotiation) section to learn how to enable it. + Of course, you can also use your favorite HTTP client to query the API. We are fond of [Hoppscotch](https://hoppscotch.com), a free and open source API client with good support of API Platform. + +## Using Data Transfer Objects and Hooking Custom Logic + +While exposing directly the data in the database is convenient for Rapid Application Development, using different classes for the internal data and the public data is a good practice for more complex projects. + +As explained in our [general design considerations](../core/design.md), API Platform allows us to use the data source of our choice using a [provider](../core/state-providers.md) and Data Transfer Objects (DTOs) are first-class citizens! + +Let's create our DTO: + +```php + [ + app_path('ApiResource'), + app_path('Models'), + ], + + // ... +]; +``` + +Then we can create the logic to retrieve the state of our `Book` DTO: + +```php +id, title: $book->title); + } +} +``` + +Register the state provider: + +```php +app->singleton(BookProvider::class, function (Application $app) { + return new BookProvider(); + }); + + $this->app->tag([BookProvider::class], ProviderInterface::class); + } +} +``` + +Apply the provider to your operation: + +```php +