Reputation: 45
here is my function.
public function get(Request $request){
$bike1 = $request->input('bike1');
$bike2 = $request->input('bike2');
//dd($bike1);
return $bike2->name;
}
When i use the dd function, the result is:
"{"id":1,"created_at":"2020-09-16T12:33:25.000000Z","updated_at":"2020-09-16T12:33:25.000000Z","name":"302r","brand":"benelli","price":800000,"displacement":300,"segment":"300cc","power":"28KW@10000 rpm","torque":"27Nm@9000rpm","fuel_delivery_system":"Efi","abs":"1","cooling_system":"Liquid","weight":155} ◀"
But when I try to access the name property(any) i get the error.
Trying to get property 'name' of non-object
What I might be missing?
Upvotes: 0
Views: 54
Reputation: 2545
You need to decode $bike2
because it's in JSON format, so you can do
$decoded_bike2 = json_decode($request->input('bike2'));
This will return an object
{#1236 ▼
+"id": 1
+"created_at": "2020-09-16T12:33:25.000000Z"
+"updated_at": "2020-09-16T12:33:25.000000Z"
+"name": "302r"
}
you can access name property like
return $decoded_bike2->name;
If you do
$decoded_bike2 = json_decode($request->input('bike2'), true);
This will return an array
array:4 [▼
"id" => 1
"created_at" => "2020-09-16T12:33:25.000000Z"
"updated_at" => "2020-09-16T12:33:25.000000Z"
"name" => "302r"
]
You can access key name like
return $decoded_bike2['name'];
For more details about json_decode()
Reference
Upvotes: 0
Reputation: 768
first decode your json then after get you name
$bike2 = json_decode($request->input('bike2'));
return $bike2->name
Upvotes: 0
Reputation: 199
It looks like $bike1 is a JSON string, before you can access it's attributes you need to decode it.
$bike1 = json_decode($request->input('bike1'));
return $bike1->name
If that doesn't work $bike1 may be an array, not an object, in that case, this should work
return $bike1['name']
Upvotes: 1