Convert json String into Object of custom class instead of stdClass.

心已入冬 提交于 2021-02-10 16:16:12

问题


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.


回答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
    ]);
}


来源:https://stackoverflow.com/questions/48838290/convert-json-string-into-object-of-custom-class-instead-of-stdclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!