SaMeEr
SaMeEr

Reputation: 381

Object access issue in laravel 5.3?

I am passing array of object in json and trying to access it in foreach loop but I got an error "Trying to get property of non-object"

JSON

{"i":[{"name":"Siddhesh mishra","mobile":"7798645895","gender":"M"},{"name":"Pratik pande","mobile":"7798645891","gender":"M"}]

foreach loop

foreach ($request->i as $key => $insrtobj) {
 if($insrtobj->name && $insrtobj->mobile && $insrtobj->gender){
 }
 else
     $response = response()->json(['data'=>[], 'error'=>1, 'success'=>0,     'error_msg'=>'request with mandatory param','message'=>'check the input data']);
}

Upvotes: 0

Views: 29

Answers (2)

patricus
patricus

Reputation: 62308

The Laravel Request object automatically decodes json input using json_decode, but it passes true as the second parameter to convert objects to arrays. So, when accessing the json data from the request, you need to treat it as an associative array, not an object.

if ($insrtobj['name'] && $insrtobj['mobile'] && $insrtobj['gender']) {

Upvotes: 1

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

Convert you JSON data into array form and use it...:

$arrData = json_decode(YOURJSONDATA, true);
foreach ($arrData as $key => $insrtData) {
 //your rest of code...
}

NOTE: When TRUE, returned objects will be converted into associative arrays. Docs

Upvotes: 0

Related Questions