How to Save Multiple Records in Database Using Laravel

In this tutorial, we will show you How to Save Multiple Records in Database Using Laravel. Mostly the beginners don’t know to save multiple records which are comes from request, So here we are going to share a best and easy way to insert the array request data in database table.

We can use more then prebuild methods like create, updateOrCreate, Insert methods for saving the data. let’s checkout the controller code for saving the multiple data in database.

Code in Controller

Suppose in your request comes mutiple array or objects and you need to all array values (one time one record) then you must use the forease here….

If the records array type then use below code..

$requestData = $request->all();

foreach ($requestData as $key => $data) {
    Service::create([
      'fltno'       =>  $data['sflt'],
      'model'       =>  $data['smodel'],
      'engine'      =>  $data['sengine'],
      'loc'         =>  $data['sloc'],
      'serviceType' =>  $data['sstye'],
      'nextSvr'     =>  $data['snsvr']
    ]);
}

If the request comes like object .. then use below code

$requestData = $request->all();

foreach ($requestData as $key => $data) {
    Service::create([
      'fltno'       =>  $data->flat_number,
      'model'       =>  $data->model,
      'engine'      =>  $data->engine,
      'loc'         =>  $data->loc,
      'serviceType' =>  $data->type,
      'nextSvr'     =>  $data->nsvr
    ]);
}

If you want to use the laravel eloquent insert() method, then you need to do this:

$data = $request->all();
$finalArray = array();
foreach($data as $key=>$value){
   array_push($finalArray, array(
                'fltno'=>$value['sflt'],
                'model'=>$value['smodel'],
                'engine'=>$value['sengine'],
                'loc'=>$value['sloc'],
                'serviceType'=>$value['sstye'],
                'nextSvr'=> $value['snsvr'] )
   );
});

Model::insert($finalArray);

Store Multiple Files in Database

If you have multiple files/images to store database then you can do this.

if ($request->hasfile('files')) {
    $files = $request->file('files');

    foreach($files as $file) {
        $name = $file->getClientOriginalName();
        $path = $file->storeAs('uploads', $name, 'public');

        File::create([
            'name' => $name,
            'path' => '/storage/'.$path
          ]);
    }
 }

If you don’t know right now read the below link…

See Here: How to insert multiple records in database using laravel

Leave a Comment