prgrm
prgrm

Reputation: 3833

Filling a table with information from other table in Laravel

I am trying to fill a table with information from other tables. Something like this:

$item = new item();
$item->save();

//this works
$item_actions-> new item_actions();
$item_actions->item_id = $item->id;
$item_actions->save();

//this doesn't work

$default_items = default_items::all();

foreach($default_items as $default_item)
{
$item_list = new item_list();
$item_list->item_id = $item->id;
$item_list->name = $default_item->name;
$item_list->save()
}

return back();

I have used dd($default_items) and it contains every single item from the default_items table. There is no error, the table is simply not filled and the program continues. The $item_actions, however, works, so there must something going on on that foreach.

Any ideas?

Upvotes: 0

Views: 461

Answers (2)

Vikash
Vikash

Reputation: 3561

I think you are missing semicolon after save method within your loop

$item_list->save();

Upvotes: 0

Diego Cespedes
Diego Cespedes

Reputation: 1353

Try just to "insert" data in the DB, if your table is called "item_lists" you can try like this:

$dataSet = [];
foreach ($default_items as $default_item) {
    $dataSet[] = [
        'item_id'  => $item->id,
        'name'    => $default_item->name,
    ];
}

DB::table('item_lists')->insert($dataSet);

Maybe laravel will require the class for DB, so just add:

use DB;

Upvotes: 2

Related Questions