function getExample4() { // get all of the hikes $hikes = \App\Hike::with('peaks', 'user')->get(); // returns 10 hikes foreach ($hikes as $hike) { // get the user $user = \App\User::find($hike->user_id); // this gets a user 10 different times, as it should $peaks = []; // get the peaks foreach ($hike->peaks as $peak) { array_push($peaks, $peak->id); } dump($peaks); // $user->peaks()->attach($peaks); } }
/** * Responds to requests to GET /hikes/edit/{id} */ public function getEdit($id = null) { $hike = \App\Hike::with('peaks')->find($id); if (is_null($hike)) { \Session::flash('flash_message', 'Hike not found.'); return redirect('/hikes'); } // get peak list $peakModel = new \App\Peak(); $peak_list = $peakModel->getPeakList(); // Create a simple array of just the peaks associated with this hike; // will be used in the view to decide which peaks should be checked off $peaks_for_this_hike = []; foreach ($hike->peaks as $peak) { $peaks_for_this_hike[] .= $peak->id; } return view('hikes.edit')->with(['hike' => $hike, 'peak_list' => $peak_list, 'peaks_for_this_hike' => $peaks_for_this_hike]); }