Why I cant return a attribute value from a PHP object to a JavaScript file using Laravel?

430 views javascript
2

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.

answered question

json_decode returns an array not an object. Use $comment['id'].

@RDev I don't knew that... Thank you so much!!

@RDev I put return $comment['id']; but still returning the 500 error :/

1 Answer

11

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.

posted this

Have an answer?

JD

Please login first before posting an answer.