Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__toString() must not throw an exception error when using string

Tags:

php

laravel

I am using Laravel 4 for a project I am working on. I need to retrieve the first comment from the post. I use the following code to do so.

$comments = Comment::where('post_id', $post->id)->first();

This successfully retrieves the first comment (I know that because I print_r-ed $comments and it returned all the right information).

However, the following line of code triggers the error __toString() must not throw an exception

<td>{{$comments->content}}</td>

When I print_r-ed that it returned type string, and returned the correct string as well. Why then would it even try to convert $comments->content to type string when it is already a string?

like image 362
jamespick Avatar asked Jan 14 '14 01:01

jamespick


2 Answers

Based off the information you've given and my experience with Laravel I'd bet that the line of code causing the exception is not the line you've put in your question.

<td>{{$comments->content}}</td>

This exception is complaining about the view throwing an exception. If this particular line was the issue you'd get a more descriptive exception about how $comments->content can't be converted into a string. You've also already tested that it is indeed a string.

I'd recommend finding where your "View" object is being echoed to the view and change it like so.

{{ View::make('yourbladefile')->__tostring() }}

This worked for me by providing a more accurate and informative exception. For more info on your exception you should check out Why it's impossible to throw exception from __toString()?

It's what gave me the idea in the first place. I know it's not a perfect answer so please let me know if this works and I'll update my answer if this turns out not be the case. Good luck.

like image 160
Drellgor Avatar answered Oct 22 '22 12:10

Drellgor


I know that this is an old question, but for future googlers (like me) there is another way to solve that error, and it is independent of your framework:

public function __toString() 
{
    try {
       return (string) $this->attributeToReturn; // If it is possible, return a string value from object.
    } catch (Exception $e) {
       return get_class($this).'@'.spl_object_hash($this); // If it is not possible, return a preset string to identify instance of object, e.g.
    }
}

You can use it with your custom class with no framework, or with an entity in Symfony2/Doctrine... It will work as well.

like image 27
Muriano Avatar answered Oct 22 '22 14:10

Muriano