我被困在编码中。如何将阵列数据发送到Laravel控制器?通常我使用this.form.something =“”将数据绑定到表单,然后使用axios将其发送到控制器,但是如何使用数组呢?我应该使用表格还是可以不使用表格发送表格?谢谢。
Vue Componenet
<template>
<form submit.prevent="submitData">
<div class="jumbotron bg-dark col-md-10 offset-md-1">
<div class="card card-body bg-dark" v-for="(user,index) in users" :key="index">
<h5>
<span class="badge badge-success mb-3 float-left">Data {{index+1}}</span>
<span style="cursor:pointer" class="float-right badge badge-danger mb-3" @click="deleteData(index)">X</span>
</h5>
<div class="row">
<div class="form-group col-md-3">
<label for="email" class="text-white">Username:</label>
<input type="text" class="form-control" id="username" v-model="user.username">
</div>
<div class="form-group col-md-3">
<label for="pwd" class="text-white">Password:</label>
<input type="password" class="form-control" id="password" v-model="user.password">
</div>
<div class="form-group col-md-3">
<label for="pwd" class="text-white">Phone Number:</label>
<input type="text" class="form-control" id="phone" v-model="user.phone">
</div>
<div class="form-group col-md-3">
<label for="pwd" class="text-white">Email</label>
<input type="email" class="form-control" id="email" v-model="user.email">
</div>
</div>
</div>
<br>
<button class="btn btn-secondary float-right" @click="addMoreData()" title="Click to add row"><span class="fa fa-plus-square"></span> Add More Data</button>
</div>
<div class="jumbotron bg-dark col-md-10 offset-md-1 ">
<button class="btn btn-success col-md-6 offset-md-3 p-3" type="submit"><span class="fa fa-plus-square"></span> Export to Microsoft Excel</button>
</div>
</form>
脚本
<script>
export default {
data(){
return{
users: [{
username:'',
password:'',
phone:'',
email:''
}]
}
},
methods:{
addMoreData(){
this.users.push({
username: '',
password: '' ,
email: '',
phone:''
});
},
deleteData(index){
this.users.splice(index,1)
},
submitData(){
}
},
mounted() {
console.log('Component mounted.')
}
}
答案 0 :(得分:0)
您的代码看起来不错,只需要将数组发送给Laravel。这是一个示例:
submitData(){
// Here we send the data to '/users/store' route,
// using POST method and 'this.users' array as data
axios.post('/users/store', this.users)
.then(function (response) {
// If the request is successful, we can do whatever we want with the response here
console.log(response);
})
.catch(function (error) {
// If there's an error, treat it here
console.log(error);
});
}
仍然使用上面的示例,在UserController中,您将收到如下数据:
public function store(Request $request)
{
/*
$request->all() contains all the data you sent
in this case, the users array, but you should always
validate it before, using FormRequest, for example:
https://laravel.com/docs/5.8/validation#form-request-validation
*/
User::create($request->all()); // Here we save all users to database
// returning the data you sent before, just for testing.
return response()->json([$request->all()]);
}