Laravel Getting id's from a table and inserting them into another table

Trying to get matching id's from a table and inserting them again in the same table under differnet relationship.

$contentPack = ContentPack::find($id);
$cloned_pack_goals = DB::table('content_pack_goal')->where('content_pack_id' , $contentPack->id)->get();
$cloned_pack_goal_ids = $cloned_pack_goals->goal_id;

Produces Exception

Property [goal_id] does not exist on this collection instance.

dd($cloned_pack_goals); outputs:

Illuminate\Support\Collection {#2466 ▼
      #items: array:2 [▼
        0 => {#3129 ▼
          +"goal_id": 4
          +"content_pack_id": 2
        1 => {#2467 ▼
          +"goal_id": 9
          +"content_pack_id": 2

How to get goal_ids from the output to insert them into the same table again but with a different relation?

$newPack = $contentPack->replicate();
DB::table('content_pack_goal')->insert(['content_pack_id' => $newPack->id,'goal_id' => $cloned_pack_goal_ids]);

Am doing something wrong when getting the ID’s and when inserting them. tried using ->first(); it works but only one id gets inserted

>Solution :

$cloned_pack_goals is a collection, so you need to exclude goal_ids from all collection records separately.
This snippet may help you:

$cloned_pack_goal_ids = DB::table('content_pack_goal')->where('content_pack_id' , $contentPack->id)->pluck('goal_id')->toArray();

foreach($cloned_pack_goal_ids as $key => $goal_id) {
   DB::table('content_pack_goal')->insert(['content_pack_id' => $newPack->id,'goal_id' => $goal_id]);


Leave a Reply