1

I have an input form named category that can have multiple value just like tags input form in stackoverflow when you asking a question
I want to get all input value from that form and insert it into category_service pivot table
I use $category = implode(",", Input::get('category')); to get the array value
And then i get Invalid argument supplied for foreach() error when try to insert it using this code:

foreach ($category as $category) {
    DB::insert('INSERT INTO category_service (category_id, service_id) VALUES (?,?)', array('$category', $service->id));
}

the tables look like this:

category_table
+----+--------------+
| id |   category   |
+----+--------------+
|  1 |  category_1  |
|  2 |  category_2  |
+----+--------------+

service_table
+----+--------------+
| id |   service    |
+----+--------------+
|  1 |   service_1  |
+----+--------------+

category_service_table //pivot table to store category id and service id
+----+--------------+-------------+
| id | category_id  |  service_id |
+----+--------------+-------------+
|  1 |      1       |      1      |
|  2 |      2       |      1      |
+----+--------------+-------------+

the var_dump result is string(3) "2,1"

1
  • Please provide some more details about your question. Also Add Category dump into your question, Commented Apr 28, 2016 at 6:24

2 Answers 2

1

$category = implode(",", Input::get('category'));

implode make a string from the array

try

$category = Input::get('category'); if (!empty($category) && is_array($category)) { foreach ($category as $val) { DB::insert('INSERT INTO category_service (category_id, service_id) VALUES (?,?)', array((int) $val, $service->id)); } }

Sign up to request clarification or add additional context in comments.

Comments

0

With PHP implode function you joining array to string and passing the string to foreach, as a result Invalid argument supplied for foreach() error. You confused with explode ? See the official documentation. Implode and Explode . Also, it better to use plural and singular naming in foreach, like foreach ($categories as $category).

And for Laravel insertion use:

DB::table('category_service')->insert(
  ['category_id' => $category, 'service_id' => $service->id]
);

Also, you put $category in a single quote and variable will not execute, it will pass as a string.

Also, you did you get $service->id ?

1 Comment

i got the $service->id value from another db query

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.