0

I want to store data from array to my Database. My code looks like this:

Vue.js

const self = this;
fetch('/api/store/devices',{
    method: 'post',
    body: JSON.stringify(self.devices),
    headers: {
      'content-type': 'application/json'
    }
  })
  .then(res => res.json())
  .then(data => {
    console.log(data);
    // do something
  })
  .catch(err => console.log(err));
}

API Route

Route::post('store/devices',[App\Http\Controllers\StorageController::class, 'store']);

StorageController.php

public function store(Request $request)
{
    //Go to array and save data
}

The data i overget looks like this:

[
  {device_id: "1245678", storage_id: 1},
  {device_id: "8784889", storage_id: 1},
  {device_id: "8457875", storage_id: 1}
]

How can i store this data?

1 Answer 1

1

First, I recommend to put the array into a field in order to make an "Open to extension, close to modification" api:

{
  'devices': [
    {device_id: "1245678", storage_id: 1},
    {device_id: "8784889", storage_id: 1},
    {device_id: "8457875", storage_id: 1}
  ]
}

Secondly, if you are trying to save a relationship instance between a device and a storage, you should use laravel relationship methods.

If its an individual model info, try the next code.

You must iterate all devices and create it as your laravel model:

public function store(Request $request)
{
    foreach ($request->devices as $device) {
        YourModel::create($device); // if you had set $fillable attribute on your model

        // or like this
        $yourModel = new YourModel();
        $yourModel->device_id = $device['device_id'];
        $yourModel->storage_id = $device['storage_id'];
        $yourModel->save(); // it saves yourModel into your db
    }
}

YourModel fillable example:

use Illuminate\Database\Eloquent\Model;

<?php
class YourModel extends Model {
    protected $fillable = [
        'device_id',
        'storage_id',
    ];
}
Sign up to request clarification or add additional context in comments.

Comments

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.