Skip to content
Advertisement

How can I select one item of an array with laravel http request?

If i run this controller in laravel:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use IlluminateSupportFacadesHttp;
use GuzzleHttpClient;
use IlluminateHttpClientResponse;
use ArrayAccess;

class ApiController extends Controller
{


function api()
{
    $barcode = 8710496976575;         
    $response = Http::get('https://api.barcodespider.com/v1/lookup?token=YOUT_TOKEN&upc=' . $barcode;);
    dd($response->json());
}}

I’ll get this result:

array:3 [▼
  "item_response" => array:3 [▼
    "code" => 200
    "status" => "OK"
    "message" => "Data returned"
  ]
  "item_attributes" => array:16 [▼
    "title" => "De Ruijter Fruit Sprinkles (Vruchten Hagel), 400 Gr (14.1 Oz), 1 Box"
    "upc" => "8710496976575"
    "ean" => "08710496976575"
    "parent_category" => "Grocery"
    "category" => "Grocery"
    "brand" => "De Ruijter"
    "model" => ""
    "mpn" => "RUI_HAGEL_FRUIT_400"
    "manufacturer" => "De Ruijter"
    "publisher" => "De Ruijter"
    "asin" => "B0044KJN1O"
    "color" => ""
    "size" => "12.8 Ounce"
    "weight" => "1 Pounds"
    "image" => "https://images.barcodespider.com/upcimage/8710496976575.jpg"
    "description" => ""
  ]
  "Stores" => array:1 [▼
    0 => array:7 [▶]
  ]
]

But I only want to return the title, upc and brand and save them as three seperated variables to store them in my database. How can i do that? If I do this:

dd($response->json("item_attributes[0]"));

I’ll get NULL;

Does anybody know how to do this in laravel?

Advertisement

Answer

Laravel converts the JSON response of Http::get() to an array, as you’re seeing with your dd output. So you should be accessing it as an associative array.

$item_attributes = $response->json()['item_attributes'];
$title = $item_attributes['title'];

// ... etc.
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement