Multilingual E-commerce API using Laravel 8.0 – Part 3 Product Resource and Product Resource Collection

Before diving into the product controller to implement the endpoint functionality, let’s create a product resource and product resource collection.

A product resource represents a single model. For ex. details of a single product

A product resource collection is a collection of models. For ex. data of a collection of products

#Step 1

Let’s first create a single product resource by using the following command.

php artisan make:resource Product

The above command should create a ProductResource.php file in app/Http/Resources/Product directory.

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'product_name' => $this->product_name,
            'product_description' => $this->product_description,
            'product_price' => $this->product_price,
            'product_id' => $this->product_id,
            'category_name' => $this->category_name,
            'category_id' => $this->category_id
        ];
    }

Resource collections allows you to transform a collection of models.

For ex. you can change the title of the product to a link to the product details page.

One other advantage of product resource is that we can add meta data to it that can be used when fetching data for this endpoint.

Now that we have created a single resource, let’s create a collection of product resources.

You can use either command below to generate a resource collection.

php artisan make:resource Product --collection

OR

php artisan make:resource ProductCollection

This should create a ProductCollection.php in app/Http/Resources/Product folder

We are going to transform the product name to include a link to the product details page

    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'product_name' => $this->translations->product_name,
            'product_price' => $this->product_price,
            'category_name' => $this->category->category_name,
            'category_id' => $this->category_id
        ];
    }

Once we have the resource and the resource collections for an entity, we can use them in the controllers to transform the data.

In the next tutorial we will see how we can use Product resource and product resource collection in the Product Controller to transform data.

Series Navigation<< Multilingual E-commerce API using Laravel 8.0 – Part 2 Database MigrationsMultilingual E-commerce API using Laravel 8.0 – Passing Information into the headers >>