I'm working with Laravel for the first time. I have a scenario where I have a Products table which contains basic details of a Product (Corrugated Box) like length, breadth, height etc. Some other details of the product is computed using the basic details within a function.
My code in the Controller looks like this:
public function viewProducts() {
/* Fetch basic details */
$prod_specs = DB::table('master_products')
->join('part_types', 'master_products.part_type_id', '=', 'part_types.id')
->join('box_types', 'master_products.box_type_id', '=', 'box_types.id')
->select('master_products.*', 'part_types.part_type', 'box_types.box_type')
->get();
/* Calculate Specs and add them to the array */
$i = 1;
$products = array();
foreach ($prod_specs as $spec) {
$products['product_code'] = $spec->product_code;
$products['part_type_id'] = $spec->part_type_id;
$products['box_type_id'] = $spec->box_type_id;
$products['length'] = $spec->length;
$products['breadth'] = $spec->breadth;
$products['height'] = $spec->height;
$products['ply'] = $spec->ply;
$products['gsm_a_base'] = $spec->gsm_a_base;
$products['gsm_a_flute'] = $spec->gsm_a_flute;
$products['gsm_b_base'] = $spec->gsm_b_base;
$products['gsm_b_flute'] = $spec->gsm_b_flute;
$products['gsm_top'] = $spec->gsm_top;
$products['roll_size'] = $this->calcRollSize($spec->height, $spec->breadth, $spec->ply, $spec->part_type_id, $spec->box_type_id);
}
return view('/layouts/masters/products-master', ['products' => $products]);
}
/* Calculate Roll Size */
private function calcRollSize($height, $breadth, $ply, $partTypeID, $boxTypeID) {
/* Some calculation */
return $rollSize;
}
I want to return $products
to my view and be able to access the basic details as well as the calculated details. Please help me achieve this.
UPDATE
I tried:
$products = DB::table('master_products')
->join('part_types', 'master_products.part_type_id', '=', 'part_types.id')
->join('box_types', 'master_products.box_type_id', '=', 'box_types.id')
->select('master_products.*', 'part_types.part_type', 'box_types.box_type')
->get();
/* Calculate Specs and add them to the collection */
foreach ($products as $product) {
$rollSize = $this->calcRollSize($product->height, $product->breadth, $product->ply, $product->part_type_id, $product->box_type_id);
$products->put('roll_size', $rollSize);
}
and got this exception: Call to a member function put() on a non-object
But according to this stackoverflow question's accepted answer it's supposed to work. Please help.
Using return view('/layouts/masters/products-master')->with(compact('products'));
you can access the full $products
variable you built in the products-master view