diff --git a/src/Illuminate/Routing/Router.php b/src/Illuminate/Routing/Router.php index f1b61dc74dcf..f1912bf0374e 100644 --- a/src/Illuminate/Routing/Router.php +++ b/src/Illuminate/Routing/Router.php @@ -18,6 +18,7 @@ use Illuminate\Routing\Events\RouteMatched; use Illuminate\Support\Collection; use Illuminate\Support\Str; +use Illuminate\Support\Stringable; use Illuminate\Support\Traits\Macroable; use JsonSerializable; use Psr\Http\Message\ResponseInterface as PsrResponseInterface; @@ -769,6 +770,8 @@ public static function toResponse($request, $response) $response = (new HttpFoundationFactory)->createResponse($response); } elseif ($response instanceof Model && $response->wasRecentlyCreated) { $response = new JsonResponse($response, 201); + } elseif ($response instanceof Stringable) { + $response = new Response($response->__toString(), 200, ['Content-Type' => 'text/html']); } elseif (! $response instanceof SymfonyResponse && ($response instanceof Arrayable || $response instanceof Jsonable || diff --git a/src/Illuminate/Support/Stringable.php b/src/Illuminate/Support/Stringable.php index e945beaf7614..65320e1bcf3f 100644 --- a/src/Illuminate/Support/Stringable.php +++ b/src/Illuminate/Support/Stringable.php @@ -5,9 +5,10 @@ use Closure; use Illuminate\Support\Traits\Macroable; use Illuminate\Support\Traits\Tappable; +use JsonSerializable; use Symfony\Component\VarDumper\VarDumper; -class Stringable +class Stringable implements JsonSerializable { use Macroable, Tappable; @@ -734,6 +735,16 @@ public function dd() exit(1); } + /** + * Convert the object to a string when JSON encoded. + * + * @return string + */ + public function jsonSerialize() + { + return $this->__toString(); + } + /** * Proxy dynamic properties onto methods. * diff --git a/tests/Support/SupportStringableTest.php b/tests/Support/SupportStringableTest.php index 851b2c0617ac..e666b2fff98b 100644 --- a/tests/Support/SupportStringableTest.php +++ b/tests/Support/SupportStringableTest.php @@ -546,6 +546,11 @@ public function testChunk() $this->assertSame(['foo', 'bar', 'baz'], $chunks->all()); } + public function testJsonSerialize() + { + $this->assertSame('"foo"', json_encode($this->stringable('foo'))); + } + public function testTap() { $stringable = $this->stringable('foobarbaz');