2

I am creating an API and I want to add extra column in the result of pagination query. For example I have price and discount in my database. I want to send discounted_price column with result set.

Here is what I have tried so far:

Controller:

$products = Products::latest()->paginate(10);
if (! empty($products)) {
    $final_prod = [];
    foreach ($products as $product) {
        $final_prod[] = $product->asFilterJson();
    }
    $data['products'] = $final_prod;
    $data['status'] = 200;
} else {
    $data['error'] = "No product available";
}

and in my Products model I have

public function asFilterJson() {
    $json = [];
    $json['id'] = $this->id;
    $json['title'] = $this->title;
    $json['category_id'] = $this->category_id;
    $json['price'] = $this->price;
    $json['description'] = $this->description;
    $json['quantity'] = $this->quantity;
    $json['discount'] = $this->discount;
    $json['type_id'] = $this->type_id;
    $json['created_by_id'] = $this->created_by_id;
    $json['created_at'] = $this->created_at;
    $json['updated_at'] = $this->updated_at;
    if($this->type_id == self::ITEM_SPECIAL) {
        $json['discounted_price'] = ($this->discount * $this->price) / 100;    }
    return $json;
}

It works fine but it removes the pagination.

yivi
  • 42,438
  • 18
  • 116
  • 138
Ashish
  • 468
  • 2
  • 8
  • 24

3 Answers3

4

you can add key and value in collection object by using map method

$products = Products::latest()->paginate(10);

$itemSpecial = self::ITEM_SPECIAL; //pass variable in closure by using use 

$products->map(function($item) use ($itemSpecial) {
     if($item->type_id == $itemSpecial) {
        $item->discounted_price = ($item->discount * $item->price) / 100; 
     }
     return $item;
});

you can used condition also in clourse

Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57
0

In Controller

public function index() {
     $products = Products::latest()->paginate(10);
     if (! empty($products)) {
        $final_prod = [];
        foreach ($products as $product) {
             $final_prod[] = $this->asFilterJson($product);
        }
        return response()->json(['status'=>'200','message'=>'Product list ','data'=>$final_prod]);
     } else {
        return response()->json(['status'=>'200','message'=>'No product available','data'=>[]]);
     }
}
// function for extra column add
static function asFilterJson($product){
    $value['discounted_price'] = ($value['discount'] * $value['price']) / 100;
    return $value;
}
-2

You can define new mutator in your model.

public function getDiscountedPriceAttribute()
{
     return ($this->discount * $this->price) / 100;
}

After than, you can use it as $this->discountedPrice

FGDeveloper
  • 1,030
  • 9
  • 23