How do I pass data to a response?

The most common task performed when extending responses, is setting additional data. Typically, for HTML responses that render from a view, this involves sending data to the view to be used as a variable. If the response returns JSON, it may be adding additional key/value pairs.

For example, if you needed to obtain customer reviews for a given product and output them on the product page, you could do the following, which passes a product to a 3rd party reviews API and then adds the reviews it returns to the response data, which is then passed to the product.twig view file ready to be loop around and outputted.

\Aero\Store\Http\Responses\ProductPage::extend(function ($page) {
    $reviews = \Acme\ReviewsAPI::forProduct($page->product);

    $page->setData('reviews', $reviews);

Another example is getting the latest 5 blog posts from a blog module and sending them to the homepage to be displayed:

\Aero\Store\Http\Responses\Homepage::extend(function ($page) {
    $posts = \Acme\BlogPosts::latest()->limit(5)->get();

    $page->setData('posts', $posts);

You can obtain the existing data set against the response builder using the getData() method and remove data using the removeData() method.

Articles in this section

Was this article helpful?
0 out of 0 found this helpful