Spadaboyz
Spadaboyz

Reputation: 369

Laravel 5.1 retrieve multiple input value and insert to db

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"

Upvotes: 1

Views: 1049

Answers (2)

dgregor
dgregor

Reputation: 56

$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)); } }

Upvotes: 1

Meathanjay
Meathanjay

Reputation: 2073

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 ?

Upvotes: 0

Related Questions