Reputation: 165
I have created an api resource like http://app.localhost/api/product/info/1000
And it works fine and returns the desired data json format.
But, when I try to execute the resource in a controller like,
$Product = Product::where('sku', $this->sku)->get()->first();
$productInfo = new ProductRes($Product);
It return the full $Product
Object, instead of json data. I have posted the screenshot of the object i have received.
Is it possible to render the resource in the same way as it does in the url?
Thanks
Upvotes: 1
Views: 3469
Reputation: 2059
Your product is always an object but laravel is using __toString magic method which basically means that what should I do when a user wants to echo an object, this is exactly what you are trying to do.
You are trying to echo $product
which triggers __toString
magic method and laravel converts it to json
for you
/**
* Convert the collection to its string representation.
*
* @return string
*/
public function __toString()
{
return $this->toJson();
}
But when you dd($product)
you are not echoing $product which means in this case you see the full object dumping out on the screen.
Upvotes: 1
Reputation: 3529
If you dump
or dd
your variable $productInfo
, it's normal it does not show you its rendered version. If you really want to dump its render, you may do this
$Product = Product::where('sku', $this->sku)->get()->first();
$productInfo = new ProductRes($Product);
dump($productInfo->resolve());
Upvotes: 3
Reputation: 4783
Laravel converts responses to JSON, if you dump the object within the controller, it will show what it really is...an object.
If you don't dump the variable, but rather do a return $productInfo
, it should cast to JSON.
Upvotes: 1