0

I got syntax error in foreach. What is the correct way of using foreach inside array of Query Builder, code as follows:

public function postItems(Request $request, $id){
    $itemid = \DB::table('items_tables')->where('category_id','=',$id)->get();       

    DB::table('store_items')->insert(
    array('user_id' => \Auth::user()->id,

        foreach($itemid as $itemids){   
          'items' => $itemids->name,
        }

          'store_id' => $id)
    );

    return view('actions.itemstore');
}

Syntax error occurred as follows in foreach:

Parse error: syntax error, unexpected 'foreach' (T_FOREACH), expecting ')'

$itemids->name variable have numerous value. I need to loop through this.

Orgil
  • 691
  • 7
  • 16
Jaseel P V
  • 318
  • 4
  • 11
  • Seriously? You are not getting error ? Have you seen ever somthing like what you wrote foreach($itemid as $itemids){ 'items' => $itemids->name, } – Rahul Jan 02 '17 at 12:17
  • i made some changes. please check it. – Jaseel P V Jan 02 '17 at 12:18
  • 2
    @JaseelBavu there is so much wrong with your code. You're trying to use `insert()` with wrongly structured array. You're using loop instead of `pluck()`. DB architecture is bad. Wrong syntax everywhere. You should really read Laravel and PHP docs. This will save you a lot of time. – Alexey Mezenin Jan 02 '17 at 12:23
  • stil remains the duplicate to the one I raised – jitendrapurohit Jan 02 '17 at 12:28

2 Answers2

0

This hould look something like this:

public function postItems(Request $request, $id){
    $itemid = \DB::table('items_tables')->where('category_id','=',$id)->get();
    foreach($itemid as $itemids) {
        $data_to_insert = [
            'user_id' => \Auth::user()->id,
            'store_id' => $id,
            'items' => $itemids
        ];
        DB::table('store_items')->insert($data_to_insert);
    }

    return view('actions.itemstore');
}
0

If you want to go full Laravel, you can write it using collections:

public function postItems(Request $request, $id)
{
    collect(\DB::table('items_tables')->where('category_id','=',$id)->get())->each(function ($item) use ($id) {
        \DB::table('store_items')->insert([
            'user_id' => \Auth::user()->id, 
            'store_id' => $id, 
            'item_name' => $item->name
        ]);
    });

    return view('actions.itemstore');
}

If you are using Laravel 5.3, you can probably drop that collect() too, because now we get collections even when using DB.

Antonio Carlos Ribeiro
  • 86,191
  • 22
  • 213
  • 204