24

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?

toesslab
  • 5,092
  • 8
  • 43
  • 62
Alen
  • 1,750
  • 7
  • 31
  • 62
  • @pc-shooter I did but now I don't remember what I did :) – Alen Apr 29 '15 at 12:05
  • 1
    If I ever fall on this problem (3 times), I need to know that this is **a problem of UTF-8** !! – w3spi Feb 11 '16 at 18:29
  • I can't believe I'm back here despite my message above. So thanks to user2778080 for [his answer](http://stackoverflow.com/a/26471039/3452348). To solve it, need to add `utf8_encode()` around utf-8 strings. Ex : `utf8_encode("Aujourd'hui à ...")` – w3spi Dec 02 '16 at 18:40

8 Answers8

16

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.

user2778080
  • 179
  • 3
  • 2
    This isn't very practicable in Laravel. How do you run `utf8_encode` on a object? – toesslab Apr 08 '15 at 08:42
  • Thanks for this! This was exactly the problem I was running into, it's a very non-descriptive error message. – KyleT Jun 26 '15 at 02:03
  • That resolved a issue giving the same error message while trying to `json_encode` an array with an element previously read from a named pipe! – wiredolphin Jun 22 '16 at 18:35
  • @Daenu You have to `utf8_encode` the string with accent return by a member of your object – w3spi Feb 27 '17 at 20:46
13

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.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
St. Jan
  • 284
  • 3
  • 17
  • And if the problem is not in the view? Desperate, please help: Some data from db works others won't... – toesslab Apr 06 '15 at 16:19
  • In my case it was a return true/false that was nested away somewhere and all calling function returned the output of the called function. Yet is you are saying it is query related.. do you output the results of the query directly? If a query is empty or went wrong it returns a false, which is a boolean. – St. Jan Apr 06 '15 at 17:39
  • it must be the query (over multiple columns) cause if I use ` ::find(id)` everything is fine. also it is only on some records . – toesslab Apr 06 '15 at 17:41
  • A so does your model allow for all the values that are returned by the db? – St. Jan Apr 06 '15 at 17:42
  • do you mean the $hidden prperty? yes it does – toesslab Apr 06 '15 at 17:43
  • Hmm I can't see your code but there could be a gazillion reasons for this. If you know which model causes the output you are already 2/3of thw way. I would output the queries that make it fail and that dont and then analize what is the difference I guess. Further more turning of any – St. Jan Apr 06 '15 at 17:47
  • Also Check your model for listeners / observers they might cause the problem – St. Jan Apr 06 '15 at 17:51
10

Create the following function

function utf8_encode_deep(&$input) {
    if (is_string($input)) {
        $input = utf8_encode($input);
    } else if (is_array($input)) {
        foreach ($input as &$value) {
            self::utf8_encode_deep($value);
        }

        unset($value);
    } else if (is_object($input)) {
        $vars = array_keys(get_object_vars($input));

        foreach ($vars as $var) {
            self::utf8_encode_deep($input->$var);
        }
    }
}

Try to do the following

utf8_encode_deep($data);
return Response::json($data);
3

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 his 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'
    );
    //...
}
Community
  • 1
  • 1
toesslab
  • 5,092
  • 8
  • 43
  • 62
2

You can try this please? im return true or false (a boolean value) and not an Response value like this

return Response::json(array(
        'error' => false,
        'message' => 'Valid Pincode'),
        200
    );
  • I just fixed the most annoying bug. Turns out I hadn't set the encoding for the php file to utf-8 and had some non-english characters in the reply message which caused this error... – toster-cx Mar 31 '16 at 09:11
2

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

Community
  • 1
  • 1
辰凌风
  • 21
  • 2
1

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.

Arjen
  • 116
  • 4
0

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

Rápli András
  • 3,869
  • 1
  • 35
  • 55