Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

saurav77's avatar

Call to a member function addEagerConstraints() on integer

 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
0 likes
5 replies
Sinnbeck's avatar

This is not a relationship

 public function getStock(){
   return $this->getOrder() + (10*0.2);
 }

You can only call with('something') on relationships.

saurav77's avatar

@sinnbeck

Then How I can I send like this

Product  | Stock 
  Laptop | 23
 Mobile  | 8

but in the blade file, I have already manage like this

@foreach($products as $product)
<td>{{$product->name}}</td>
<td>{{product->getStock()</td>
@endforeach
 result will come like above table

So how can I send data like above but in JSON data?
I hope you understand my question, sir?
Thanks for responding
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

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
     ])
saurav77's avatar

@sinnbeck can I ask you a question?

What if I need to use select() for stock and name only? like

$products=Product::select('stock','product_name')->get();

I think error will come like a column not found (stock) or something? or is there any way so I can send stock and name only ?

Please or to participate in this conversation.