blade - How to best get results from 3 different tables based on ID matches in Laravel. -
trying products , variants particular supplier. can products easy enough, can't figure out how best variants matching product_id , send view. variants.product_id matches product.id
this works (getting products supplier)
public function suppliers($id) { $supplier = supplier::orderby('company_name', 'asc')->find($id); $products = supplier::find($id)->products; $data = []; $data['supplier'] = $supplier; $data['products'] = $products; return view('admin.purchasing.supplier-details', $data); }
i've tried variants without luck.
controller:
public function suppliers($id) { $supplier = supplier::orderby('company_name', 'asc')->find($id); $products = supplier::find($id)->products; $variants = array(); foreach ($products $product) { $product_id = $product->id; $variants[] = variant::find($product_id); } $data = []; $data['supplier'] = $supplier; $data['products'] = $products; $data['variants'] = $variants; return view('admin.purchasing.supplier-details', $data); }
view:
@foreach($products $product) <tr> <td>{{ $product['title'] }}</td> @foreach($variants $variant) @if($variant->product_id == $product['id']) <td>${{ $variant->price }}</td> @else <td>not set</td> @endif @endforeach </tr> @endforeach
any tips appreciated.
first of , should have relation set on models make work
like exemple :
supplier.php
public function products() { return $this->hasmany('app\product'); }
product.php
public function variants() { return $this->hasmany('app\variant'); } public function supplier() { return $this->belongstomany('app\supplier'); //in case have 1 supplier each product change belongsto }
variant.php
public function products() { return $this->belongstomany('app\product'); //not sure if should manytomany or 1 many , deppends on did }
anyway can this
controller
public function suppliers($id) { $data = supplier::where('id',$id)->orderby('company_name', 'asc')->with('products.variants')->first(); //you supplier products associated him variants foreach product return view('admin.purchasing.supplier-details')->with('data',$data); // loop $supplierwithproducts->products results (dd variable check output) }
view
{{ $data->name }} // supplier name since supplier model starting point @foreach($data->products $product) //loop products related supplier {{ $product->name }} //shows product name (depends on database collumns @foreach($product->variants $variant) // loops variants in current product {{ $variant->name }} // shows variants @endforeach @endforeach
if copy , paste code might not work ,but give idea how should handle relations in laravel (levrage eloquent relations)
check more informations