Have you seen this lovely error while working in Laravel?
Method Illuminate\View\View::__toString() must not throw an exception
I have seen it and it's incredibly annoying. I have found out two reasons why this error gets thrown. I just want to help people not take hours and hours of time.
View answers & situations below. :)
Situation 1: Trying to print out a value in an array.
Answer 1: Try printing out the array. Are you sure it's an array? I've gotten this error when it was an object instead of an array. Try doing a print_r and seeing what you get.
Situation 2: You have this associated array like this:
When you try to access post_images array directly within a View, it throws an error. No. Matter. What. You. Do.
Answer 2: Check in all the places where you are calling the View. What happened here is that I was trying to access the same view somewhere else in an area where I wasn't giving the post_images array. Took FOREVER to figure out.
I hope this helps someone else. :) I just know the error I kept getting didn't help me anywhere.
There is a very simple solution: don't cast View object to a string.
Don't:
echo View::make('..');
orecho view('..');
Do:
echo View::make('..')->render();
orecho view('..')->render();
By casting view, it uses
__toString()
method automatically, which cannot throw an exception. If you callrender()
manually, exceptions are handled normally. This is the case if there is an error in the view - laravel throws an exception.This actually is a PHP limitation, not Laravels. Read more about this "feature" here: https://bugs.php.net/bug.php?id=53648
a similar error is:
FatalErrorException in FooController.php line 0: Method App\Models\Foo::__toString() must not throw an exception
and it was just a bad assignment:
$foo.= new Foo;
instead of:
$foo = new Foo;