This is my problem.
I have a model called Product that defines a relation like this
Product.php
public function maintenanceById($maintenanceId){
return $this->belongsToMany(Maintenance::class, 'product_maintenance')->where('maintenance_id', '=', $maintenanceId)->withPivot(['price', 'code']);
}
I use this method in a view like so
@foreach($maintenance as $value)
@if($product->maintenanceById($value->id)->getResults())
<th>
{{$product->maintenanceById($value->id)->getResults()[0]->pivot->price}}
</th>
@else
<th></th>
@endif
@endforeach
getResults
returns an array that has a single object in it so I have to access the object within using getResults()[0]
. Is there a way to make the returned value into an object so I can simply do this:
$product->maintenanceById($value->id)->getResults()->pivot->price
EDIT: Ive tried this and it works
public function maintenanceById($maintenanceId){
return $this->belongsToMany(Maintenance::class, 'product_maintenance')->where('maintenance_id', '=', $maintenanceId)->withPivot(['price', 'code'])->get();
}
Then in the view
@foreach($maintenance as $value)
@if(!$product->maintenanceById($value->id)->isEmpty())
<th>£ {{$product->maintenanceById($value->id)->first()->pivot->price}}</th>
@else
<th></th>
@endif
@endforeach
But when I try the following code it doesn't work.
public function maintenanceById($maintenanceId){
return $this->belongsToMany(Maintenance::class, 'product_maintenance')->where('maintenance_id', '=', $maintenanceId)->withPivot(['price', 'code'])->first();
}
@foreach($maintenance as $value)
@if(!$product->maintenanceById($value->id)->isEmpty())
<th>£ {{$product->maintenanceById($value->id)->pivot->price}}</th>
@else
<th></th>
@endif
@endforeach