ABD
ABD

Reputation: 889

Inserting into a table from the array in laravel

I am getting this array from the view

When i do return $BlogData['Tag'];

The result is

 ["1", "2"]

How can i insert this into each record i.e., a fresh entry in the table ?

S.No | Tag
   3 |  1
   4 |  2

Like the above given in the table

When i try

foreach ($BlogData['Tag'] as $x) 
        {
        echo $x;
        Tag::create($x);
        }

I am getting this error

message: "Argument 1 passed to Illuminate\Database\Eloquent\Model::create() must be of the type array, string given, 

Upvotes: 2

Views: 2781

Answers (3)

bdtiger
bdtiger

Reputation: 521

For Model::create() the argument must be array. You have passed a single value not an array. Please have a look http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_create

For create method you have to $fillable array in your model

protected $fillable = [
    'Tag'
];

In your controller

$data = $BlogData['Tag'];
foreach ($data as $key=>$value)
{  $data_attribute = array('Tag'=>$value);
   Tag::create($data_attribute);
}

Upvotes: 1

Oli Soproni B.
Oli Soproni B.

Reputation: 2800

foreach ($BlogData['Tag'] as $x) 
{
    # Tag index will be the table column name
    # and its value is $x
    $pass = array(
        'Tag' => $x
    );
    Tag::create($pass);
}

here is a good link of nice way to insert multiple rows using laravel

Bulk Insertion in Laravel using eloquent ORM

Upvotes: 0

Joseph Silber
Joseph Silber

Reputation: 220136

foreach ($BlogData['Tag'] as $x) 
{
    Tag::create(['Tag' => $x]);
}

Upvotes: 2

Related Questions