1

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. enter image description here

Is it possible to render the resource in the same way as it does in the url?

Thanks

2
  • What do you mean by execute the resource in a controller? Return it? Commented Apr 18, 2020 at 11:33
  • By execute i mean when an trying to return it through my controller. $Product = Product::where('sku', $this->sku)->get()->first(); $productInfo = new ProductRes($Product); Commented Apr 18, 2020 at 11:35

3 Answers 3

3

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());
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, this has fixed my issue
You're welcome, remember tagging a post as your accepted answer.
->get() is redundant. It is sufficient Product::where('sku', $this->sku)->first();
1

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.

2 Comments

Thank you, now i understand how it works, thank you for the quick reply
No problem. Accept the answer if it was the one you were looking for :)
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.