ahmad almasri
ahmad almasri

Reputation: 59

Laravel access JSON object in controller

I have this array in the controller after the submitted form holds in variable $product.

[
    {
        "id": 2,
        "name": "nancy",
        "cost": 34,
        "quantity": 0,
        "barcode": 12345,
        "category_id": 2,
        "created_at": "2020-07-05T16:04:10.000000Z",
        "updated_at": "2020-07-09T04:06:09.000000Z"
    },
    {
        "id": 5,
        "name": "jk",
        "cost": 100,
        "quantity": 2,
        "barcode": 147258,
        "category_id": 2,
        "created_at": "2020-07-08T20:34:56.000000Z",
        "updated_at": "2020-10-18T13:09:16.000000Z"
    }
]

How can I access the properties in objects like id, name, barcode ?

Upvotes: 0

Views: 6669

Answers (2)

Tayyab Hussain
Tayyab Hussain

Reputation: 1838

Just decode it, use json_decode

$products = json_decode($products, true);  // When TRUE, JSON objects will be returned as associative arrays

foreach($products as $product){
    echo $product['id']; 
}

Upvotes: 1

Haseeb Javed
Haseeb Javed

Reputation: 52

If you want to make it as array of array.

$products = json_decode($products, true);  // Return array of array.

foreach($products as $product){
    echo $product['name']; 
}

Upvotes: 2

Related Questions