Преобразование строки json в объект пользовательского класса вместо stdClass.

мой файл order.php имеет

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

И в моем контроллере я получаю cartItems следующим образом

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'));


}

И в приведенном выше коде dd($item) будет выводиться следующим образом

   {#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"
}

но я хочу, как показано ниже.

   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"
}

Как я могу добиться этого в laravel.


person Abhilash.k.p    schedule 17.02.2018    source источник
comment
Возможный дубликат json_decode для пользовательского класса   -  person faintsignal    schedule 26.09.2018


Ответы (1)


Добавьте true в качестве второго параметра в вашу функцию декодирования, например:

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

Я бы создал модель CartItem:

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

Создайте экземпляр каждого из них, например:

// 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
    ]);
}
person Community    schedule 17.02.2018