The table distributor_requisition_items
has the columns : requisition_id
, product_id
, measuring_unit_id
, quantity
In the model DistributorRequisition.php
, I have:
class DistributorRequisition extends Model
{
public function items()
{
return $this->belongsToMany('App\Product','distributor_requisition_items',
'requisition_id','product_id')->withPivot('measuring_unit_id','quantity');
}
}
In the controller I have :
class CurrentInventoryController extends Controller
{
public function distributor_inventory(Request $request)
{
$distributor_requisition=DistributorRequisition::get();
$distributor_requisitions_all= $distributor_requisition->items;
// this line produces an error
return view('admin.current_inventory.distributor-inventory',
compact('distributor_requisitions_all','stores',.....));
}
}
In the distributor-inventory.blade.php
, I have :
@foreach($distributor_requisitions_all as $aP)
{{$aP->items->measuring_unit_id}}
@endforeach
I get the following error :
Exception in Collection.php line 1527: Property [items] does not exist on this collection instance.
in Collection.php line 1527 at Collection->__get('items') in CurrentInventoryController.php line 64
And the line 64 in the controller has : $distributor_requisitions_all= $distributor_requisition->items;
So how to use the eloquent model method items
in the controller so that I can access the distributor_requisitions_all
variable in the view to extract values from it ?
$distributor_requisition=DistributorRequisition::get();
is a collection of Model DistributorRequisition, while items is a method inside the model that is why it is giving you an error .. you can't directly call a Model method from a collection .. and to solve your issue what you have to do is
in your function
public function distributor_inventory(Request $request)
{
$distributor_requisition=DistributorRequisition::get();
return view('admin.current_inventory.distributor-inventory',
compact('distributor_requisition','stores',.....));
}
and in your view
@foreach($distributor_requisition as $aP)
// {{ $aP->items->measuring_unit_id }}
// that will give you error since $aP->items is another collection of many model item what you can do is add another loop
@foreach($aP->items as $item)
$item->pivot->measuring_unit_id }}
@endforeach
@endforeach
use with() method instead of get().
public function distributor_inventory(Request $request)
{
$distributor_requisition=DistributorRequisition::with('items');
return view('admin.current_inventory.distributor-inventory', ['distributor_requisitions_all' => $distributor_requisition]);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.