diff --git a/src/Illuminate/Support/Stringable.php b/src/Illuminate/Support/Stringable.php index c24d19e6a923..017917baa097 100644 --- a/src/Illuminate/Support/Stringable.php +++ b/src/Illuminate/Support/Stringable.php @@ -4,9 +4,10 @@ use Closure; use Illuminate\Support\Traits\Macroable; +use JsonSerializable; use Symfony\Component\VarDumper\VarDumper; -class Stringable +class Stringable implements JsonSerializable { use Macroable; @@ -722,6 +723,16 @@ public function dd() exit(1); } + /** + * Convert the object into something JSON serializable. + * + * @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 1986d050de9c..930d99ac4aef 100644 --- a/tests/Support/SupportStringableTest.php +++ b/tests/Support/SupportStringableTest.php @@ -545,4 +545,11 @@ public function testChunk() $this->assertInstanceOf(Collection::class, $chunks); $this->assertSame(['foo', 'bar', 'baz'], $chunks->all()); } + + public function testJsonSerializable() + { + $this->assertSame('"laravel-php-framework"', json_encode($this->stringable('LaravelPhpFramework')->kebab())); + $this->assertSame('["laravel-php-framework"]', json_encode([$this->stringable('LaravelPhpFramework')->kebab()])); + $this->assertSame('{"title":"laravel-php-framework"}', json_encode(['title' => $this->stringable('LaravelPhpFramework')->kebab()])); + } }