Learn API Resource in Laravel

Tram Ho

Introduce

  • API (Application Programming Interface) is an interface that a computer system or application provides so that service requests can be made from other computer programs and allow data to be exchanged. Back and forth between them through methods GET , POST , PUT , DELETE , PATCH .
  • When building an API, you need to convert the Eloquent model and JSON data returned by the user’s application. The Laravel resource class allows you to easily convert between model and model collections in JSON.

Create Resource

  • To create a resorce class, you can use the Artisan command window Example: php artisan make:resource Product .
  • By default, resources will be generated in the app/Http/Resource in your project. Resource uses IlluminateHttpResourceJsonJsonResource .

Resource Collections

  • In addition to creating resources and converting models, resources can transform collections of models. This allows the returned data to include links related to the collection of the resource.
  • To create a resource collection, you should use the --collection parameter at the end of the resource creation statement. Or you can add the Collection suffix after the resource name, the resource collection uses the IlluminateHttpResourceJsonResourceCollection .

JsonResource class

  • A resource class represents a model that needs to be transformed in a JSON structure.
  • Create resource class Product php artisan make:resource Product

  • Each resource class has a predefined method toArray returns an array of properties of the object that should be converted into JSON when sending a response.
  • We can access the properties of the common model $this .

Resource Collections

  • If you want to return a collection of a resource or a paginate, you can use the collection method when creating a resource instance in the route or controller.

  • Note: The above example does not allow any additional data when being returned to the collection. If you want to add resources, you need to create a Collection

  • After defining the resource collection, it can be called on the route or controller.

  • When returning a resource collection from a route.
  • The $preserveKey attribute allows you to know if the collection keys are kept public $preserveKeys = true;
  • The $collects property allows you to change the default Collection mapping

References

Share the news now

Source : Viblo