framework: json_encode returning false

Hi, im using

PHP 7.0.4-7ubuntu2 (cli) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
    with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2016, by Zend Technologies

And Laravel Framework version 5.1.34 (LTS)

When giving the below value to json_encode it is returning false rather than string

Illuminate\Database\Eloquent\Collection {#3502
     all: [
       App\User {#3487
         last_active: "",
       },
     ],
   }

but it is returning correct string in php5-fpm.

two days back only i upgraded to php7 and observed this error.

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 24 (18 by maintainers)

Most upvoted comments

As a workround, you can use json_encode($obj->jsonSerialize()) instead of json_encode($obj). or you may modify the Illuminate\Support\Collection->jsonSerialize() to the following codes:

$res = array_map(function ($value) {
    if ($value instanceof JsonSerializable) {
        return $value->jsonSerialize();
    } elseif ($value instanceof Jsonable) {
        return json_decode($value->toJson(), true);
    } elseif ($value instanceof Arrayable) {
        return $value->toArray();
    } else {
        return $value;
    }
}, $this->items);
json_encode([]); //clear the json_last_error
return $res;

Today i installed the php 7.0.7 and this is fixed

Try json_last_error_msg first