可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
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.
回答2:
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.