Sorting computed data in laravel

  laravel, sorting

So I am working on filter API for an e-commerce application. I have finished doing filtering data with a query to get the product model and passed the collection to the product resource to generate JSON resource with computed data. this is how my JSON response looks like:

     [
        {
            "id": 2693,
            "name": "Product A",
            "coverImage": "http://abc.url/storage/product/cover_image1584083807.PNG",
            "wishlist": false,
            "attributeProductId": 5204,
            "type": "none",
            "stockQuantity": 10,
            "price": 900,
            "discountedPrice": 900,
            "isDiscounted": false,
            "discountPercent": 0,
            "ratingAndReview": {
                "total": 4,
                "averageRating": 3
            }
        },
        {
            "id": 2182,
            "name": "Product B",
            "coverImage": "http://abc.url/storage/product/cover_image1576822643.jpg",
            "wishlist": false,
            "attributeProductId": 4566,
            "type": "none",
            "stockQuantity": 22,
            "price": 465,
            "discountedPrice": 465,
            "isDiscounted": false,
            "discountPercent": 0,
            "ratingAndReview": {
                "total": 10,
                "averageRating": 3.5
            }
        }
      ]

Here "discountedPrice", "isDiscounted", "ratingAndReview" are computed in Product Resource and I want to sort the data with those key-values.
I tried this method:

$unsortedData  = json_decode($products->toJson(), true);
$sortedData = collect($unsortedData['products'])->sortBy('ratingAndReview.total', SORT_REGULAR, true);

This method does work but the response speed of the API will be very high and even I need to send data with custom pagination. so calling the API every time for pagination will make the application too slow.

What could be the solution to this? Please suggest to me if there are other best ways to achieve the same result in an efficient way?
Thank you.

Source: Laravel

Leave a Reply