Damon
Damon

Reputation: 4524

Laravel: How can I use json_decode in my view?

I am trying to figure out the best way to get the properties from a serialized array in my blade template.

MyController.php

$cart = Cart::findOrFail($id);
...
return view('view', ['cart' => $cart]);

So in this case $cart has many items (objects) within it that is getting passed to the view.

cart.blade.php

...

@each('show', $cart->items()->get(), 'item')

...

In this view I can access things in this way:

show.blade.php

<p>$item->name</p>
<p>$item->color</p>
...

But $item also has a serialized attribute that contains things like sku, weight, quantity etc.

// $item->serialized_item = {"id":123,"quantity":5,"...} (string)

So in my show.blade.php view I need to do something like:

json_decode($item->serialized_item)

Right now I am just importing another view to help keep things clean, but I don't think this is the best way.

cart.blade.php

...
@include('detail', ['attributes' => item->serialized_item])

detail.blade.php

<?php
    $foo = json_decode($item->serialized_item, true);
?>

<p>{{$foo['quantity']}}</p>  // 5

This method works, but it seems like a hack.

Upvotes: 1

Views: 999

Answers (1)

Ivan Gabriele
Ivan Gabriele

Reputation: 6920

You will need to change your item model to create a setSubAttributes() method :

public function setAttributes() {
    $attributes = json_decode($this->serialized_item, true);

    $this->id = $attributes ['id'];
    $this->quantity = $attributes ['quantity'];
}

and call it in your controller to prepare the date for the views :

$cart = Cart::findOrFail($id);
$items = $cart->items()->get();

foreach ($items as &$item) {
  $item->setAttributes();
}

so that you can now call your attributes directly in your detail.blade.php view.

EDIT

I didn't try it but you could even call it straight into your item model constructor, so that you can avoid to call it within the controller :

public function __construct()
{
    $this->setAttributes();
}

Upvotes: 1

Related Questions