【问题标题】:I get the 500 error when I try to return a value from PHP object/array. But it's ok return all the object当我尝试从 PHP 对象/数组返回值时,出现 500 错误。但是可以返回所有对象
【发布时间】:2019-02-20 08:35:49
【问题描述】:

我正在尝试在 Laravel 中创建一个简单的应用程序,用于从数据库发送和获取 cmets。

我将 PHP 和 JS 与 AJAX 一起使用。但是当我尝试获取完整的评论对象时:

PHP

    public function UpdateComment(Request $request){
        $id = $request->id;
        $jsonCode = DB::table('comments')->where('id', $id)->get();
        $comment = json_decode($jsonCode);
        return $comment
    }

效果很好:

[{…}]
  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)

这正是我期望看到的,完整的 PHP 对象。 但是当我尝试返回或仅使用同一个对象的单个属性时,我收到了 500 错误...

return $comment->id;

.

POST http://laravelhost/update-comment 500 (Internal Server Error)

我是PHP初学者,所以应该是一个很简单的错误。

【问题讨论】:

  • json_decode 返回一个数组而不是一个对象。使用 $comment['id']。
  • @RDev 我不知道...非常感谢!!
  • @RDev 它有效!谢谢!!发布您的答案,以便我可以完成此问题。请

标签: javascript php json laravel object


【解决方案1】:

您收到错误 500,因为 json_decode() 返回一个数组,而不是一个对象。 因此,要访问您的数据,请使用数组语法,而不是对象运算符:

return $comment['id']

【讨论】:

    【解决方案2】:

    试试这个:

    public function UpdateComment(Request $request){
        $id = $request->id;
        $record = DB::table('comments')->where('id', $id)->get();
        return $record;
    }
    

    你不需要json_decode() DB::table()...调用的返回值。

    【讨论】:

    • 好吧,我需要在同一个函数中使用这些值做很多其他事情。这就是我尝试解码的原因。
    • DB::table() 返回一个数组,您可以按原样返回。你可以围绕它做很多事情,但你不应该 json_decode() 不是 json 字符串的东西。
    • 返回只是为了验证数据是否好转。其实thats真实代码。
    【解决方案3】:

    要检索单行,您应该使用 first() 而不是 get()

    $comment = DB::table('comments')->where('id', $id)->first();
    echo $comment->id;
    

    https://laravel.com/docs/5.7/queries

    【讨论】:

      【解决方案4】:

      你可以使用

      $comment = DB::table('comments')->where('id', $id)->first();
      return $comment->id;
      

      $comment = DB::table('comments')->where('id', $id)->get();
      return $comment[0]->id;
      

      如果您在获取数据后使用 json_decode,对象将 转换为数组。所以,你必须使用 $arrayname['keyname'] 获取数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-16
        • 1970-01-01
        • 1970-01-01
        • 2016-03-25
        • 2017-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多