Search code examples
laravelcollectionsreplicationlaravel-5.3

Replicate Laravel collection - Laravel 5.3


Im replicating a trips table. On the trips form, there is a dropdown to select species. A user can select many species to. Im having trouble replicating this species table beacuse its in its own table, and its a collection. So using "replicate" wont work.

This is how Im replicating the trips table right now:

public function replicateTrip (Request $request, $slug, $id) {

        $listing = $request->user()->listings()->where('slug', $slug)->first();
        $trip = $listing->trips()->where('id', $id)->first();

        $replicateTrip = Trip::find($trip->id);
        // This is how im getting the species from the species table
        $replicateSpecies = DB::table('species_trip')->where('trip_id', $id)->get();

        $newTask = $replicateTrip->replicate();

        $newTask->save();

        return redirect()->back();

}

If I DD the $replicateSpecies variable when cloning my current trip, I get:

My Collection

I need to replicate the species array from my orginal trip into the species table, and I cant just use "replicate", because its a collection.

So my question is how would I replicate this collection? Or if there is another method of doing this?


Solution

  • You can try it as:

    public function replicateTrip (Request $request, $slug, $id) {
    
        $listing = $request->user()->listings()->where('slug', $slug)->first();
        $trip = $listing->trips()->where('id', $id)->first();
    
        $replicateTrip = Trip::find($trip->id);
    
        // This is how im getting the species from the species table
        $replicateSpecies = DB::table('species_trip')->where('trip_id', $id)->get();
    
        $newTask = $replicateTrip->replicate();
    
        $newTask->save();
    
        $replicateSpecies->each(function ($item, $key) use($newTask) {
            $copy = $item->replicate();
            $copy->trip_id = $newTask->id;
            $copy->save();
        })
    
        return redirect()->back();
    

    }