You will want view()->render() so it's the raw view data?
return response()->json([
'body' => view('product', compact('product'))->render(),
'product' => $product,
]);
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
hi,
How do i make a Response::json calling a result from a view? i know its a strange thing to do as you can directly output json without views, but in this case we want a view returning a real view, and a view returning json, so i could use blade functionality.
product.blade.php:
{{$product}}
routes.php option one:
Route::get('/product/{id}', function ($id) {
$product = \App\Product::with('category')->find($id);
return view('product')->with('product',$product);
}
routes.php option two:
Route::get('/product/{id}', function ($id) {
$product = \App\Product::with('category')->find($id);
return Response::json(array(view('product')->with('product',$product), 'product' => $product));
}
routes.php option three:
Route::get('/product/{id}', function ($id) {
$product = \App\Product::with('category')->find($id);
return Response::json(array('body' => View::make('product',array('product'=>$product))->render()));
}
option two returns my second 'product' => $product as json, but not my blade view? got that one from: http://laravel.io/forum/08-23-2014-return-view-in-json
option three returns
{
body: "{"id":1,"artikel_id":"test1","category_id":1,"artnr":"test1a
etc.
Bart
thnx @d3xt3r the 2 posts together did the trick:
i changed:
routes.php:
Route::get('/product/{id}', function ($id) {
$product = \App\Product::with('category')->find($id);
return response()->json([
'product' => view('product')->with('product',$product)->render()
]);
});
into:
routes.php:
Route::get('/product/{id}', function ($id) {
$product = \App\Product::with('category')->find($id);
return response(view('product',array('product'=>$product)),200, ['Content-Type' => 'application/json']);
});
and changed product.blade.php from:
{!! $product !!}
to
{!! json_encode($product) !!}
and it works! thanks!
Bart
Please or to participate in this conversation.