theUnforgiven
10 months ago
107
10
Laravel

multidimensional array from Vue to Laravel

Posted 10 months ago by theUnforgiven

I'm having a bit of brain freeze and can't figure out how to get the data from these two forms from VueJS to save with Laravel.

Here's the code with VueJS

<label>Reading Type</label>
<select name="reading_type[]" class="form-control">
    <option value="">Please Select</option>
    <option v-for="(type, index) in reading_type" 
            :value="type.tags"
            :key="type.index" 
            :id="type.id"
    >
        {{ type.value }}
    </option>
</select>
<div class="row mt-2">
    <div class="col">
        <label>Gas Reading</label>
        <input type="number" name="reading[]" class="form-control">

        <label>Water Reading</label>
        <input type="text" name="reading[]" class="form-control">

        <label>Electric Reading</label>
        <input type="number" name="reading[]" class="form-control">
    </div>
    <div class="col">
        <label>Reading Date</label>
        <input type="date" class="form-control" name="reading_date[]">

        <label>Reading Date</label>
        <input type="date" class="form-control" name="reading_date[]">

        <label>Reading Date</label>
        <input type="date" class="form-control" name="reading_date[]">
    </div>
</div>

Here's what I have currently with Laravel:

$readings = $request->get('reading');   
$dates = $request->get('reading_date');
$types= $request->get('reading_type');

for($i = 0; $i < $readings; $i++){
    $reading = new MeterReadings;
    $reading->user_id       = user()->id;
    $reading->entered_by    = user()->name;
    $reading->meter_type    = $types[$i];
    $reading->property_id   = $request->property;
    $reading->reading       = $readings[$i];
    $reading->reading_date  = $dates[$i];
    $reading->save();
}

But it's not saving or throwing some errors like Undefined offset: 2

within Vue I send a post request like so:

addReading: function() {
        let readingForm = document.getElementById('readingForm');
        let formData = new FormData(readingForm);

        axios.post('/api/addReadings/', formData);
}

If I dd() the request I get the full request:

array:4 [
  "property" => "161"
  "reading_type" => array:2 [
   0 => "moved_out"
   1 => "move_in"
 ]
 "reading" => array:6 [
    0 => "001"
   1 => null
   2 => null
   3 => "002"
   4 => null
   5 => null
 ]
"reading_date" => array:6 [
  0 => "2018-12-12"
  1 => null
  2 => null
  3 => "2018-12-13"
  4 => null
  5 => null
 ]
]

Any help/advice to get these to save as individual rows would be awesome, sorry it's a lame question, just having a really bad brain freeze and it's been one of them weeks, so help greatly appreciated.

Please sign in or create an account to participate in this conversation.