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.

4
  • Seriously? You are not getting error ? Have you seen ever somthing like what you wrote foreach($itemid as $itemids){ 'items' => $itemids->name, } Commented Jan 2, 2017 at 12:17
  • i made some changes. please check it. Commented Jan 2, 2017 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. Commented Jan 2, 2017 at 12:23
  • stil remains the duplicate to the one I raised Commented Jan 2, 2017 at 12:28

2 Answers 2

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');
}
Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

still shows the same error
It shows error on this line foreach($itemid as $itemids){
Rewrote it using Laravel collections. I`m not sure of the names of your columns, but you must know them, right?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.