I have two Model classes with a oneToMany relation like this
App\Carclass Car extends Model
{
public $timestamps = true;
protected $fillable = [
'name',
'price'
];
public function parts ()
{
return $this->hasMany('App\Part');
}
}
App\Part
class Part extends Model
{
public $timestamps = false;
protected $fillable = [
'name',
'price'
];
public function car ()
{
return $this->belongsTo('App\Car');
}
}
The client makes a POST request with a JSON representing a Car with a nested Array of Parts
{
"name": "Fiat Punto",
"price": 15000,
"parts": [
{
"name": "wheel",
"price": 300
},
{
"name": "engine",
"price": 5000
}
]
}
Is there a way to save the Car model and create the relations in just one hit?
I tried to do this in my controller but it doesn't work:
...
public function store (Request $request) {
$input = $request->all();
Car::create($input);
}
...
PS: I already know how to do the task with a foreach
or array_reduce
, just wondering if laravel could do that for me
-- Edit --
Here is how i implemented the controller right now:
...
public function store (Request $request) {
$input = $request->all();
$car = Car::create($input);
$parts = array_reduce(
$input['parts'],
function ($carry, $item) {
array_push($carry, new Part($item));
return $carry;
},
[]
);
$car->parts()->saveMany($parts);
}
...
Any improvement is welcome