lundi 4 septembre 2017

Save multiple rows to DB with Laravel 5.5

I have 6 inputs (could be more), two of them has type='file'

<input type="text" class="form-control" name="name[]" placeholder="Name">
<input type="text" class="form-control" name="description[]" placeholder="description">
<input type="file" class="form-control-file" name="img[]">
<input type="text" class="form-control" name="name[]" placeholder="Name">
<input type="text" class="form-control" name="description[]" placeholder="description">
<input type="file" class="form-control-file" name="img[]">

and I'm expecting to save data like this by one query.

    ID|page_id|name|description|img
    1 |15     |ABC |DESCR 1    |file1.jpg
    2 |15     |DEF |DESCR 2    |file2.jpg
    3 |15     |GHI |DESCR 3    |file3.jpg

Here is the part of my controller, it saves data but only once as u can see.

public function store(Request $request)
{
   if($request->hasFile('img')){
        $fileNameExt = $request->file('img')->getClientOriginalName();
        $fileName = pathinfo($fileNameExt, PATHINFO_FILENAME);
        $fileExt = $request->file('img')->getClientOriginalExtension();
        $fileNameToStore = $fileName.'_'.time().'.'.$fileExt;
        $pathToStore = $request->file('img')->storeAs('public/images',$fileNameToStore);
    }

   $info = new Info;
   $info->name = $request->input('Name');
   $info->description = $request->input('Description');
   $info->img = $fileNameToStore;
   $info->page_id= $page->id; //sync with page id (previous table)
   $info->save();   
}

I can save multiple rows if I have inputs with one 'name' (watch below), but can't do it with more different 'name' inputs and with type="file". I tried to save data by using different ways( loops,Model::insert() ), but thats the best result I got...

foreach ($request->input('Name') as $key => $value) {           
        $info = new Info;
        $info->name = $value;
        $info->page_id = $page->id; //sync with page id
        $info->save();
    }

Any hints, please?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire