zettz's avatar
Level 1

Insert array as new value in database table

Hi there, I need help on how to insert array into table, I already looking for many example, but I keep getting it as null.

The problem:

User input data separated by comma in textbox field. So how can I split that and insert it to database as new record for each inputted data without comma?

Thx.

0 likes
2 replies
sutherland's avatar
Level 28

You just need to use PHP's explode function. Here's an idea:

// The user input
$input = 'one,two,three';

// Convert to an array
$items = explode(',', $input);

// This is where you insert your data.
// You could also use the query builder to insert all at
// once, but I do one at a time so I can track model events.
foreach ($items as $item) {
    \App\Item::create(['name' => $item]);
}
1 like
zettz's avatar
Level 1

@sutherland Hi there, I got it work after following your answer, I didn't think of using explode before.

Thx for your answer and time.

Please or to participate in this conversation.