(Looks like I solved my own problem, if only someone could answer question in the Update 1 and check my own solution for the problem in Update 2. Thank you.)
Trying to clone Invoice model with related Items.
Getting Call to undefined method Illuminate\Database\Query\Builder::associate()
error.
Any help is greatly appreciated!
Invoice.php
public function items(){
return $this->hasMany('App\Item');
}
Item.php
public function invoice(){
return $this->belongsTo('App\Invoice');
}
InvoiceController.php
public function copy(Invoice $invoice){
$copy = $invoice->replicate(['number']);
foreach($invoice->items as $item) $copy->items()->associate($item);
$copy->push();
return redirect('/invoices/' . $copy->id . '/edit')->with('alerts', ['Invoice has been copied']);
}
Update 1
I guess, I semi-figured this out. Parent cloned model should be saved first to receive an ID before calling for saveMany
on children nodes. Looks like push
method cannot be used here either.
I am still puzzled, why I cannon use associate
and push
methods in this scenario...
Update 2
Turns out this method was not creating cloned items, instead, it was updating the ones it was trying to clone, which is weird... What I did is replicate
items inside a loop (replication does not exists in relations like belongsTo
). So my final code is:
public function copy(Invoice $invoice){
$copy = $invoice->replicate(['number', 'url_key']);
$copy->url_key = strtolower(str_random(8));
$copy->save();
foreach($invoice->items as $item) $copy->items()->save($item->replicate(['type_id']));
return redirect('/invoices/' . $copy->id . '/edit')->with('alerts', ['Invoice has been copied']);
}