Reputation: 365
Can anyone help me how to display the product name? I have productquantity stored in my purchase record and now I want to display the product name in productquantity record.
I have 3 Tables
Purchaserecord
Productquantities
Product
Controller:
public function createpurchase(Request $request)
{
$purchasenumber = $request->purchasenumber;
$dataPurchaseRecord = Purchaserecord::where('purchasenumber','=',$purchasenumber)->with('productquantity')->get();
return view('admin.createpurchase',compact('purchasenumber', 'dataPurchaseRecord'));
}
View:
@forelse($dataPurchaseRecord as $Request)
<tr>
<td> <a class="name">{{$Request->productquantity->prod_id}}</a></td>
<td><em class="productprice">{{$Request->quantity}}</em> </td>
<td style="width:100px;" class="td-actions"><a href="javascript:;" class="delete-modal btn btn-mini btn-danger" data-id="{{$Request->id}}" ><i class="icon-minus"> </i>Remove</a> </td>
</tr>
@empty
<tr><td colspan='4'><em>No Data</em></td></tr>
@endforelse
Model:
public function product()
{
return $this->belongsTO('App\Product', 'prodquantityid', 'id');
}
{{$Request->productquantity->prod_id}}
should be display the product name instead of the id
How can I build the model and view on this?
Upvotes: 1
Views: 48
Reputation: 64466
You could define your models as
Class Purchaserecord extends Model{
public function productquantity()
{
return $this->belongsTo('App\Productquantities', 'prodquantityid');
}
}
Class Productquantities extends Model{
public function product()
{
return $this->belongsTo('App\Product', 'prod_id');
}
public function purchaserecords()
{
return $this->hasMany('App\Productquantities','prod_id');
}
}
Class Product extends Model{
public function productquantities()
{
return $this->hasMany('App\Productquantities','prod_id');
}
}
Now eager load your data like
$dataPurchaseRecord = Purchaserecord::where('purchasenumber','=',$purchasenumber)
->with('productquantity.product')
->get();
In loop you access product object as $Request->productquantity->product->name
Upvotes: 1