In my (Laravel) application receive a JSON which looks like:
{
"name": "order 1",
"customer": "cus123",
"orderItems": [
{
"amount": 1,
"name": "cola",
"price": "2.10"
},
{
"amount": 3,
"name": "fanta",
"price": "2.00"
},
]
}
I have create 2 models in Laravel, one Order
and one OrderItem
. I want to parse the received JSON to one Order
instance $order
.
I can get this done so by doing this in my OrderController
:
class OrderController extends Controller
{
public function store(Request $request) {
$order = new Order();
$order->forceFill($request->toArray());
}
}
It’s possible to access properties now like $order->name
and $order->customer
in the store
function of the controller. When i access the $order->orderItems
i receive an array with "orderItemsbut as array, not as instance of
OrderItem`.
I want that $order->orderItems
returns an array of OrderItem
instances. I tried the following in Order
but this does not work as 'orderItems'
is not a OrderItem::class
but is an array with multiple "OrderItems".
protected $casts = [
'orderItems' => OrderItem::class,
];
How can i achieve that $order->orderItems
returns an array of OrderItem
instances?
Thanks for any help in advance!
2
Answers
Try to add the following to your controller
.
You can also create multiple children in single command.
Read here for more info https://laravel.com/docs/9.x/eloquent-relationships#the-save-method
You can move this into your model as extra custom method.
For example:
And you call it as
$order->saveOrderItems($orderItems);
P.S.
Dont forget to declare relationship in Order model.
I think you are confuse with the whole Model relationship. Checkout the documentation here, you need to define proper relationship and foreign key between your Order and OrderItem model.
Then your model should be like this;
Then your store method