mercredi 11 octobre 2017

Eloquent Collections, how to modify the data of each registry contained in results?

I have the following situation, Im trying to modify the price of products displayed in a platform.

Everything works ok for only 1 product (eg: product view) but I dont know what I have to do in order to modify the price of each product in an eloquent collection.

this is my code:

ProductRepository.php:

public function CalcPrice($product){
    $x = $product->price; //eg 5
    $y = 4;
    $amount= $x + $y;
    return $amount;
}

For the details view of each product inside ProductController I have the following code and everything works perfect:

public function details($id){
  $product = $this->product->getProductById($id);
  $productprice = $this->product->getCalcPrice($product = $product);
  return view('products.view',compact('product','productprice'))
}

On the other hand, my idea is to use the code contained in ProductRepository.php function CalcPrice in a collection.

My main doubt is what do I have to do, because in a collection probably I can have a variable $category in order to retrieve all products in a category, but I will not have a variable for each $product (for a product id like in details).

What can I do in order to eg:

modify each product price contained in a collection of a category using CalcPrice function code?

eg: of code: productrepository.php

public function AllProductsInCategory($catid)
    {
        return App\Product::where('categoryid', $catid)
        ->get();
}

but each product displaying their ($product->price + 4) as CalcPrice performs. thanks!.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire