I have 3 models
Event has many Shifts
Shift belongs to Event
Shift has many ShiftWorkers
ShiftWorker belongs to Shift
when i get to save all models at once through html form with this store method in controller:
public function store(EventsForm $request)
{
//dd($request->all());
// save event
$event = Auth::user()->events()->create($request->all());
$total_shifts = count($request->shift_start);
$shifts = [];
for ($s = 0; $s <= $total_shifts-1; $s++ ) {
array_push($shifts, new Shift(['shift_start' => $request->shift_start[$s], 'shift_end' => $request->shift_end[$s]]));
}
// save shifts
$event->shifts()->saveMany($shifts);
$workers = [];
for ($w = 0; $w <= $total_shifts-1; $w++ ) {
array_push($workers, new ShiftWorker(['quantity' => $request->quantity[$w], 'hour_wage' => $request->hour_wage[$w]]));
}
// save workers
$event->shifts()->shift_workers()->saveMany($workers);
i get this error
Call to undefined method Illuminate\Database\Query\Builder::shift_workers()
How can i save my third Model (ShiftWorker) ?
Each shift has a hasMany
, so you can't call shift_workers()
on a collection.
You've to loop, like below:
foreach ($event->shifts as $shift) {
$shift->shift_workers()->saveMany($workers);
}