[英]I get the 500 error when I try to return a value from PHP object/array. But it's ok return all the object
I'm trying to create a simple application in Laravel that sends and gets comments from the database. 我正在尝试在Laravel中创建一个简单的应用程序,该应用程序可以从数据库发送和获取注释。
I'm using both PHP and JS with AJAX. 我在AJAX中同时使用PHP和JS。 But when I try to get the full comment object: 但是,当我尝试获取完整的注释对象时:
PHP 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. 这正是我期望看到的完整的PHP对象。 But when I try to return or simply use a single attribute of this same object, I got a 500 error... 但是当我尝试返回或仅使用同一对象的单个属性时,出现了500错误...
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. 我是PHP的初学者,因此应该是一个非常简单的错误。
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. 您不需要json_decode()DB :: table()...调用的返回值。
To retrieve a single row you should use first() instead of get() 要检索单行,应使用first()而不是get()
$comment = DB::table('comments')->where('id', $id)->first();
echo $comment->id;
https://laravel.com/docs/5.7/queries https://laravel.com/docs/5.7/queries
You are getting error 500 because json_decode()
returns an array, not an object. 由于json_decode()
返回一个数组,而不是一个对象,因此出现错误500。 So to access your data use array syntax, instead of object operator: 因此,要使用数组语法而不是对象运算符来访问数据:
return $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. 如果在获取数据后使用json_decode,则对象将转换为数组。 So, you have to use $arrayname['keyname'] for fetching data. 因此,您必须使用$ arrayname ['keyname']来获取数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.