当我尝试从PHP对象/数组返回一个值时,我收到500错误。 但是可以归还所有对象
I'm trying to create a simple application in Laravel that sends and gets comments from the database.
I'm using both PHP and JS with AJAX. But when I try to get the full comment object:
PHP
public function UpdateComment(Request $request){
$id = $request->id;
$jsonCode = DB::table('comments')->where('id', $id)->get();
$comment = json_decode($jsonCode);
return $comment
}
Works well:
[{…}]
0:
author_id: 6
comment_date: "2018-09-15 09:53:01"
comment_text: "23423434234"
history: ""
id: 60
last_update: "2018-09-15 00:00:00"
>proto__: Object
length: 1
>proto__: Array(0)
This is exactly what I expected to see, the full PHP object. But when I try to return or simply use a single attribute of this same object, I got a 500 error...
return $comment->id;
.
POST http://laravelhost/update-comment 500 (Internal Server Error)
I'm a beginner in PHP, so it should be a very simple error.
You are getting error 500 because json_decode()
returns an array, not an object.
So to access your data use array syntax, instead of object operator:
return $comment['id']
Try this:
public function UpdateComment(Request $request){
$id = $request->id;
$record = DB::table('comments')->where('id', $id)->get();
return $record;
}
You don't need to json_decode() the return value of DB::table()... call.
To retrieve a single row you should use first() instead of get()
$comment = DB::table('comments')->where('id', $id)->first();
echo $comment->id;
You can either use
$comment = DB::table('comments')->where('id', $id)->first();
return $comment->id;
or
$comment = DB::table('comments')->where('id', $id)->get();
return $comment[0]->id;
If you are using json_decode after fetching data, object will converted to array. So, you have to use $arrayname['keyname'] for fetching data.