Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

BartHuis's avatar

How to make a blade view returning json?

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

0 likes
27 replies
bashy's avatar

You will want view()->render() so it's the raw view data?

return response()->json([
    'body' => view('product', compact('product'))->render(),
    'product' => $product,
]);
2 likes
BartHuis's avatar

@bashy yes, i want my raw json output, to use with an other application, but i want the json to go through the blade renderer. (ps: i updated my first post with a third try / fail ;P )

bashy's avatar

I don't really understand what you mean. You're sending product through to the view already. What exactly isn't working?

Show expected output and what you have with what I posted.

Updated my reply so it's more readable with compact().

BartHuis's avatar

@bashy it first returns the rendered view, with the code rendered as html, and then it returns my product opject as json, i want the first one, the view, rendered as the second one...

https://snag.gy/p8XDOC.jpg

bashy's avatar

Zero clue what you mean, sorry :D

Thijmen's avatar

You can echo your Model straight in your controller, it transforms into JSON output when you try to view it. So, no need to do it in a view :)

bashy's avatar

@Thijmen They already have that as a JSON object which is why I'm confused.

d3xt3r's avatar

If your view can return a valid json then

return response(view('product',array('product'=>$product)),200, ['Content-TYpe' => 'application/json']);
2 likes
Thijmen's avatar

@bashy In my opinion you shouldn't use views for creating a JSON response. You can create an array and echo it in your controller.

bashy's avatar

@Thijmen Reading the thread at this part makes me think they want to have HTML data as well as JSON?

It's a strange thing to do as JSON is default for output 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.

BartHuis's avatar

@bashy @thijmen i know i know :P

thats why i started with: "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."

If i use the standard json method, i can't do things with the json in my blade file (such as https://github.com/laracasts/matryoshka blade.php: @cache @endcache and such things)

So that's why i want a blade view rendering, returning valid json.

bashy's avatar

Would be best to show how you're displaying the JSON in the blade view... Probably escaping it when you don't want to?

BartHuis's avatar

at the moment i only tried:

{{!! $product !!}}

and

{{$product}}

in my blade views

BartHuis's avatar

@thijmen i tried multible forum treads and twitters to jefrey, but no response from anyone how to use it to store my objects instead of views. so my colleage said it would meybe be a good thing to put the json in views, so when we come at the point were going to use real views, we can easaly switch, as we want to have json and views along eathother in the future, it would be nice to have it both in blade files, and not at diferent places....

BartHuis's avatar

@Thijmen i also foloowed the whole video, but maybe i need a second view to understand how to use it separate, as i want to use the functionality of having child objects, the whole idea of russian doll caching

d3xt3r's avatar

To me, a blade view is nothing more than a template, can be used for HTML, json, XML and whatever, you wish. You need to ensure that the output from view in valid, in this case a valid JSON string.

{!! json_encode($product) !!}

// Or you can construct the json from $product object looping through the attributes one by one.
1 like
BartHuis's avatar
BartHuis
OP
Best Answer
Level 2

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

3 likes
BartHuis's avatar

@Thijmen maybe we'll still look at the other option, but for now, this was the initial answer i needed on this question

Prullenbak's avatar

But since

view('product',array('product'=>$product))

returns

json_encode($product)

You're basically doing

    return response(json_encode($product),200, ['Content-Type' => 'application/json']);

which in turn translates to:

return Response::json($product);

So still not sure what you're trying to do :)

BartHuis's avatar

@Prullenbak

in you're case, i couldn't use the blade functionality, now i can...

the blade functionality i want to use, is the matryoshka/russian doll caching

and yes, that one seems to be usable in an other way to cache my whole object. But since nobody replayd on my topic (https://laracasts.com/discuss/channels/laravel/cache-objects-without-views-1) how to cache objects instead of blade's, we decided to first try to use the blade way to do it... now it works, now we'll look at other ways

Thijmen's avatar

@BartHuis With the Cache facade you can still do something like this:

$usersCache = Cache::get('all_users');
if ( $usersCache == null ) {
    $usersCache = User::all();
    Cache::put('all_users', $usersCache, 30);
}

In this example you can store objects as cache, and cache them for 30 minutes.

BartHuis's avatar

@Thijmen but you don't get parent child constructions then right? (btw, i guess were two dutch people talking english to eachother now so other people can read this later on? ;P )

Thijmen's avatar

@BartHuis Dutch indeed ;) You can do something like User::with('roles', 'items')->get() as the cache. In that way, it'll eager-load the relation and store it with the cache.

BartHuis's avatar

this is the construction you can make with blade:

resources/views/cards/_card.blade.php:

@cache($card)
    <article class="Card">
        <h2>{{ $card->title }}</h2>

        <ul>
            @foreach ($card->notes as $note)
                @include ('cards/_note')
            @endforeach
        </ul>
    </article>
@endcache

resources/views/cards/_note.blade.php:

@cache($note)
    <li>{{ $note->body }}</li>
@endcache
BartHuis's avatar

@Thijmen in that way, it wont cache the roles and items seperately right? the idea of russian doll caching is that, in your case, if only roles changes, the user will be build again, build roles again, but get items from the last time he cached. i guess in your example the whole cache item will be build again? so hell get items from the DB again?

Please or to participate in this conversation.