問題描述
Laravel:帶有axios的表單不保存 (Laravel: form with axios not saving)
我正在用 vue.js
前端編寫用戶編輯功能。
axios 部分:
sendUserData(){
axios.post('/api/saveUser', {
id: this.id,
name: this.name,
email: this.email,
password: this.password
},
{
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token')
}
}
).then(response => {
console.log(response.data);
if(response.data == 'success'){
this.$emit('userSaveSuccess')
} else {
this.$emit('userSaveError')
}
});
輸出是 success
,但在數據庫中沒有任何變化。我也嘗試過 Postman,那時數據已更改,因此控制器工作正常。這部分是怎麼回事?
編輯:
我的控制器方法:
public function saveUser($name = '', $email = '', $password = ''){
$id = request('data.id', 0);
$name = request('data.name', $name);
$email = request('data.email', $email);
$password = request('data.pswrd', $password);
Log::info(request());
if($id == 0){
$saveUser = new User;
} else {
$saveUser = User::find($id);
if($name == ''){
$name = $saveUser ‑> name;
}
if($email == ''){
$email = $saveUser ‑> email;
}
}
$saveUser ‑> name = $name;
$saveUser ‑> email = $email;
if($password != ''){
$saveUser ‑> password = bcrypt($password);
}
if($saveUser‑>save()){
return 'success';
} else {
return 'error';
}
}
參考解法
方法 1:
Your data needs to be sent within the data
property.
axios.post('/api/saveUser', {
// don't forget the data property
data: {
id: this.id,
name: this.name,
email: this.email,
password: this.password
}
},
// ...
It would probably be a good idea to set up some validation in your controller too, as that would have made it apparent you weren't receiving the appropriate data.
EDIT: Thank you for posting the controller method.
You don't need to use data.*
when retrieving the request data in the controller. This is simply where they go in axios to pass them as request variables. Also, the pswrd
parameter in your controller does not match password
which you are sending with axios.
public function saveUser($name = '', $email = '', $password = ''){
// get your parameters from the request helper
// you don't need to use data.* here
$id = request('id', 0);
$name = request('name', $name);
$email = request('email', $email);
$password = request('password', $password); // this is not 'pswrd'
// ...
// you should consider switching to the Hash facade to allow
// hashing to be configured within `/config/hashing.php`
if ($password != ''){
$saveUser‑>password = Hash::make($password);
}
// ...
}
As a final note, it's important to know that Laravel only updates an entry if the data has changed. If you send the same values, there will be no change. Since your method involves retrieving the existing name and email when those request values are empty, this might explain why it appears that nothing is saving in the database.
To force an update of the timestamps without any changes, you would need to call the ‑>touch()
method on the model.
(by Feralheart、matticustard)