PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, March 3, 2022

[FIXED] Replicate Laravel collection - Laravel 5.3

 March 03, 2022     collections, laravel, laravel-5.3, replication     No comments   

Issue

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();

}



Answered By - Amit Gupta
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing