private function manageSpacecraftFlightRelation() { $currentSpacecraftFlight = $this->mission->spacecraftFlight; $spacecraftInput = array_pull($this->input['mission']['spacecraft_flight'], 'spacecraft'); // If the spacecraft flight input exists (create/update) if (!is_null($this->input['mission']['spacecraft_flight'])) { $spacecraftFlight = $currentSpacecraftFlight->count() == true ? $this->mission->spacecraftFlight->fill($spacecraftInput) : new SpacecraftFlight($spacecraftInput); // Create spacecraft if it is not being reused or otherwise find it and update it $spacecraft = array_key_exists('spacecraft_id', $spacecraftInput) ? Spacecraft::find($spacecraftInput['spacecraft_id']) : new Spacecraft(); $spacecraft->fill($spacecraftInput); $spacecraft->spacecraftFlights()->save($spacecraftFlight); $spacecraftFlight->mission()->associate($this->mission); // Now manage astronautFlights and astronauts $this->manageAstronautFlightsRelation(); // If the input spacecraft flight does not exist and the current spacecraft flight does (delete) } elseif (is_null($this->input['mission']['spacecraft_flight']) && !is_null($currentSpacecraftFlight)) { $this->mission->spacecraftFlight->delete(); // Also delete any astronaut flights & spacecraft (Maybe manage with database cascading?) } }