1

my order.php file has

 /**
 * Encode the cart items from json to object
 * @param $value
 * @return mixed
 */
public function getCartItemsAttribute($value){
   return json_decode($value);
}

And in my controller i fetch cartItems as follows

public function orderDetails(Order $order){

   $address = implode(',',array_slice((array)$order->address,2,4));

foreach ($order->cartItems as $item){
    dd($item);
       }
   return view('/admin/pages/productOrders/orderDetails',compact('order','address'));


}

And in above code dd($item) will outputs as follows

   {#422 ▼
  +"id": 4
  +"user_id": 2
  +"product_id": 1
  +"quantity": 1
  +"deleted_at": null
  +"created_at": "2018-02-16 08:12:08"
  +"updated_at": "2018-02-16 08:12:08"
}

but I want as below.

   Cart {#422 ▼
  +"id": 4
  +"user_id": 2
  +"product_id": 1
  +"quantity": 1
  +"deleted_at": null
  +"created_at": "2018-02-16 08:12:08"
  +"updated_at": "2018-02-16 08:12:08"
}

How can i achieve this in laravel.

Abhilash.k.p
  • 408
  • 7
  • 18
  • Possible duplicate of [json\_decode to custom class](https://stackoverflow.com/questions/5397758/json-decode-to-custom-class) – faintsignal Sep 25 '18 at 23:00

1 Answers1

1

Add true as a second parameter to your decode function like:

/**
 * Decode the cart items from json to an associative array.
 *
 * @param $value
 * @return mixed
 */
public function getCartItemsAttribute($value){
   return json_decode($value, true);
}

I would create a CartItem model:

// CartItem.php
class CartItem extends Model {
   public function order() {
        return $this->belongsTo(Order::class);
   }
}

Instantiate each one like:

// Controller.php
$cartItems = [];
foreach ($order->cartItems as $item){
    // using json_encode and json_decode will give you an associative array of attributes for the model.
    $attributes = json_decode(json_encode($item), true);
    $cartItems[] = new CartItem($attributes);

    // alternatively, use Eloquent's create method
    CartItem::create(array_merge($attributes, [
        'order_id' => $order->id
    ]);
}