Level 102
This is not a relationship
public function getStock(){
return $this->getOrder() + (10*0.2);
}
You can only call with('something') on relationships.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have a model like this
public function getOrder(){
//Query
return order;
}
//Calculation
public function getStock(){
return $this->getOrder() + (10*0.2);
}
So In Controller, i need to send data but error occurs like call to a member function addEagerConstraints() an integer.I need to fetch data in external API project .
public function apiData(){
$products=Product::with('getStock')->get();
return response()->json([
'data'=>$products
])
}
But I do like this
public function apiData(){
$products=Product::with('getStock')->get();
foreach($products as $product){
dd($product->getStock());
}
return response()->json([
'data'=>$products
])
}
Then Result will come like -3.0
I need to fetch data in external API project .So i need to send those products and individual Stock Value of its products in API. So
The easiest way it with appends
On the model
$appends = [
'stock'
];
public function getStockAttribute(){
return $this->getOrder() + (10*0.2);
}
And controller
$products=Product::get();
return response()->json([
'data'=>$products
])
Please or to participate in this conversation.