Norgul
Norgul

Reputation: 4783

How to access data in a json string

So I'm sending from Ionic app to API via POST request an array of condiments which are on mobile part represented as checkboxes. I want to get the checkboxes which are checked so I can create table rows accordingly.

The method that is called upon route triggering has this part:

$condiments = Input::only('condiments');

foreach ($condiments as $condiment) {
    if ($condiment['checked'] == 1) {
        OrderCondiment::create([
            'order_item_id' => $orderItem, 
            'condiment_id' => $condiment->id
        ]);
    }
}

But I get Illegal string offset 'checked' error. I tried with $condiment->checked but then I get Trying to get the property of non-object error...what am I missing...besides coffee

EDIT

dd($condiments)

array:1 [
  "condiments" => "[{"id":1,"name":"ut","price":3,"created_at":null,"updated_at":null,"checked":1},{"id":2,"name":"ipsam","price":5,"created_at":null,"updated_at":null,"checked":1},{"id":3,"name":"dolores","price":10,"created_at":null,"updated_at":null,"checked":1},{"id":4,"name":"esse","price":3,"created_at":null,"updated_at":null,"checked":0},{"id":5,"name":"aliquid","price":1,"created_at":null,"updated_at":null,"checked":0},{"id":6,"name":"sunt","price":3,"created_at":null,"updated_at":null,"checked":0},{"id":7,"name":"saepe","price":1,"created_at":null,"updated_at":null,"checked":0},{"id":8,"name":"impedit","price":10,"created_at":null,"updated_at":null,"checked":0},{"id":9,"name":"dolores","price":4,"created_at":null,"updated_at":null,"checked":0},{"id":10,"name":"veniam","price":2,"created_at":null,"updated_at":null,"checked":0}]"
]

Upvotes: 0

Views: 86

Answers (1)

Ehsan
Ehsan

Reputation: 459

convert string to array

$condiments = Input::only('condiments');
$condiments= json_decode( $condiments['condiments']) ;
foreach ($condiments as $condiment) {
    if ($condiment->checked == 1) {
        OrderCondiment::create(['order_item_id' => $orderItem, 
                                'condiment_id' => $condiment->id]);
    }
}

Upvotes: 8

Related Questions