The Stringable Interface in Responses
Return a Stringable directly from a route and Laravel will render it as an HTTP response — no explicit conversion needed.
Overview
Any object implementing Stringable (or PHP's __toString) can be returned directly from a route or controller. Laravel will automatically convert it to a response. This pairs beautifully with the fluent Str::of() / str() helper.
Usage
Route::get('/slug-preview', function () {
return str(request('title'))
->slug()
->prepend('/blog/');
});
// GET /slug-preview?title=Hello World → "/blog/hello-world"
This also works with any custom class that implements Stringable:
class Greeting implements \Stringable
{
public function __construct(
private string $name,
) {}
public function __toString(): string
{
return "Hello, {$this->name}!";
}
}
Route::get('/greet', fn () => new Greeting('Taylor'));
// "Hello, Taylor!"
When to Use
- Quick API endpoints that return a computed string
- Prototyping routes that return formatted text
- Returning value objects that have a natural string representation