The Response content must be a string or object im

2019-02-11 18:17发布

I'm trying to return a rendered View using Response::json but I'm getting this error:

The Response content must be a string or object implementing __toString(), \"boolean\" given."

This is my code:

$posts = Post::where( ... )->orderBy( ... )->get();
$data['posts'] = View::make("posts.partials.loadHome")->with("posts", $posts)->render();
$data['msg'] = "ok";

return Response::json($data);

If I var_dump($data) I get this:

<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=2)</i>
  'posts' <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>'&lt;div class=&quot;post postGrid&quot; data-id=&quot;1864&quot;&gt;&#10; &lt;a target=&#39;_blank&#39; href=&quot;http://objavi.net/posts/1864&quot;&gt;&lt;img src=&quot;http://objavi.net/&quot; id=&quot;imgWrap&quot; data-original=&quot;/thumbs/YAo4wFzIpl76.jpg&quot; class=&quot;lazy&quot; alt=&quot;Deset manje poznatih činjenica o Jozefu Staljinu&quot;&gt;&lt;/a&gt;&#10;  &#10;   &lt;div id=&quot;bodyPreview&quot;&gt;&#10;     &#10;       &lt;a target=&#39;_blank&#39; href=&quot;http://objavi.net/posts/1864&quot;&gt;&lt;h1 class=&quot;previewTitle&quot;&gt;Deset manje poznatih činjenica o Jozefu Staljinu&lt;/h1&gt;&lt;/a&gt;&#10;&#10;     &lt;h3 id=&quot;postInfo&quot;&gt;&#10;                         &lt;a class=&quot;paint&quot; href=&quot;/category/17&quot;&gt;zanimljivosti&lt;/a&gt;&#10; '...</font> <i>(length=12172)</i>
  'msg' <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>'ok'</font> <i>(length=2)</i>
</pre>

This is posts.partials.loadHome view:

@foreach($posts as $post)

<div class="post postGrid" data-id="{{ $post->id }}">
    <a target='_blank' href="{{ URL::action('PostsController@show', $post->id) }}">{{ HTML::image(null, $post->title, ["id" => "imgWrap", "data-original" => $post->getThumb(), "class" => "lazy"]) }}</a>

    <div id="bodyPreview">

        <a target='_blank' href="{{ URL::action('PostsController@show', $post->id) }}"><h1 class="previewTitle">{{ e($post->title) }}</h1></a>

        <h3 id="postInfo">
            @foreach($post->categories as $c)
                <a class="paint" href="/category/{{ $c->id }}">{{ $c->name }}</a>
            @endforeach
        </h3>

        <h2 class="bodyPreview">{{ strip_tags(truncString($post->body, 160)) }}</h2>

        <div id="createdBy">
            <a href="{{ URL::action('UsersController@show', $post->user()->first()->id) }}">
                {{ HTML::image($post->user()->first()->getAvatar(), $post->user()->first()->username, ["width" => "32", "height" => "32"]) }}

                {{{ $post->user()->first()->username }}}
            </a>
            <label id="timeAgo">{{ localDate($post->created_at); }}</label>
        </div>
    </div>
</div>
@endforeach

I tested this on localhost and everything works fine. What could be the problem?

8条回答
霸刀☆藐视天下
2楼-- · 2019-02-11 18:49

That you didn't create $data = array(); and the local and remote PHP versions differ.

查看更多
不美不萌又怎样
3楼-- · 2019-02-11 18:54

Check to make sure there aren't any illegal characters. I had this issue once and ran utf8_encode on the string and that solved the issue.

查看更多
Ridiculous、
4楼-- · 2019-02-11 18:55

first :

this error only happened when you return false;

it means Response::json($data) == false .

second :

some character that json can't encode

perhaps,some ASCII char (like 0x00~0x31 that can't display) in your string...

so,json encode return false

查看更多
Juvenile、少年°
5楼-- · 2019-02-11 19:00

Although this question is a bit old and your problem probably solved by now, I thought this may be relevant for others. Tl;dr: use DB::statement("SET NAMES 'UTF8'"); just before retrieving the results from the database.

Your data is probably stored in a character set other than UTF-8 in the database, for instance lantin1. As an alternative for encoding the DB results in your application, you might consider letting the DB handle this.

When using MySQL, you can specify the character set to communicate to the server with using SET NAMES 'charset_name'. This specifies to the server that queries are sent using this character set, and asks the server to return results using this character set. (see documentation)

Laravel expects UTF-8 data. So, in this case you can issue a statement asking to communicate in UTF-8 before selecting results:

DB::statement("SET NAMES 'UTF8'");
$posts = Post::where( ... )->orderBy( ... )->get();

If necessary, you can always switch back to another character set afterwards.

查看更多
家丑人穷心不美
6楼-- · 2019-02-11 19:02

In my case the error

the Response content must be a string or object implementing __toString(), "boolean" given.

apeared also even when eliminating view variables one by one or when using another view (as suggsested by WillyBurb). So hes answer was not working for me.

After a long research, I found out that the problem was caused by the following columns:

  • created_at
  • updated_at
  • deleted_at.

After adding them to the $hidden property, the error was gone.

from the docs:

Hiding Attributes From Array Or JSON Conversion

Sometimes you may wish to limit the attributes that are included in your model's array or JSON form, such as passwords. To do so, add a hidden property definition to your model:

class User extends Eloquent {
    //...
    protected $hidden = array(
        'password',
        'remember_token',
        'deleted_at',
        'created_at',
        'updated_at'
    );
    //...
}
查看更多
干净又极端
7楼-- · 2019-02-11 19:03

I ran in to this blog post and think it gives a pretty good idea for fixing it:

This kind of error will kill you if yo are going to debug it Or trace it step by step, you will never find the solution because this error happens in response, I mean that it will be detected by the framework only after the response is ready to be rendered ,So it is as the message said "the response is boolean". Often it will happen in the view that some variables affect the response content . Just check the view variables one by one ,and remove each of them the try to run again . you will find the variable that cause this error. But before going in this path try to change the view by any other view page (blade-template) and see if the error is still there . if it is not , then the problem in the view page.

查看更多
登录 后发表回答