1

How can I save the following array values in my sql table?

Array (
   [0] => "/path/to/file/file_name1.jpeg"
   [1] => "file_name1.jpeg"
)
Array (
   [0] => "/path/to/file/file_name2.jpeg"
   [1] => "file_name2.jpeg"
)

Following is my table structure,

id - int - auto inc
path - varchar(200)
name - varchar(50)

Thanks in Advance.

0

3 Answers 3

2

You can insert an array of data with insert() method:

$data = [
    ['path' => '/path/to/file/file_name1.jpeg', 'name' => 'File 1'],
    ['path' => '/path/to/file/file_name2.jpeg', 'name' => 'File 2'],
    ['path' => '/path/to/file/file_name3.jpeg', 'name' => 'File 3'],
];

Model::insert($data);

Or:

....
DB::table('some_table')->insert($data);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @alexey, I am returning that array value from function. Am passing that returned value to save into database. Pls suggest me how to pass that array value to save into database.
I guess you should create new question, describe the situation and post some code, so we'll be able to help you with that too.
0

You can use foreach and create method as:

foreach ($array as $key => $value) {
    ModelName::create(['path' => $value[0], 'name' => $value[0]]);
}

Remember to add path and name in your model's fillable attribute.

2 Comments

This will work, but this will create DB query for each insertion.
It's use full when you have an observer for create method.
0

You can add multiple values with the following

$data = array(
    array('name'=>'value', 'path'=>'value'),
    array('name'=>'value', 'path'=>'2048'),
    //...
);

Model::insert($data);

You can find more here https://laravel.com/docs/5.3/queries#inserts

1 Comment

if you want to update timestamps you will have to pass 'created_at'=> $now, 'modified_at'=> $now Hope it will help

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.