我正在使用Laravel& amp; VueJS。当我提交创建表单时,我收到此消息错误:[Vue警告]:渲染错误:“TypeError:无法读取未定义的属性'id'
这里,我的createUser方法:
export default {
data(){
return {
user: {
firstname: '',
lastname: '',
email: '',
password: ''
},
errors: [],
users: [],
update_user: {}
}
},
mounted(){
this.readUsers();
},
methods: {
createUser(){
axios.post('user', {
firstname: this.user.firstname,
lastname: this.user.lastname,
email: this.user.email,
password: this.user.password
}).then(response => {
this.reset();
if (response.data.message == "Error"){
this.errors.push("L'utilisateur que vous tentez d'ajouter existe déjà!")
}else{
this.users.push(response.data.user);
}
})
},
readUsers(){
axios.get('user')
.then(response => {
this.users = response.data.users;
});
},
}
}
这里是我从DB显示所有用户时的表格。显示用户正常工作。
<table class="table table-bordered table-striped table-responsive" v-if="users.length > 0">
<tbody>
<tr>
<th>#</th>
<th>Nom</th>
<th>Prénom</th>
<th>Adresse e-mail</th>
<th>Action</th>
</tr>
<tr v-for="(user, index) in users">
<td>{{ user.id }}</td>
<td>{{ user.lastname }}</td>
<td>{{ user.firstname }}</td>
<td>{{ user.email }}</td>
<td>
<button @click="initUpdate(index)" class="btn btn-success btn-xs">Éditer</button>
<button @click="deleteUser(index)" class="btn btn-danger btn-xs">Supprimer</button>
</td>
</tr>
</tbody>
</table>
来自Laravel的我的用户模型:
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'id',
'firstname',
'lastname',
'email',
'password'
];
protected $hidden = [
'password', 'remember_token',
];
}
完成后,我的UserController方法:
public function store(Request $request)
{
$this->validate($request, [
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required',
'password' => 'required'
]);
$user = User::create([
'firstname' => request('firstname'),
'lastname' => request('lastname'),
'email' => request('email'),
'password' => Hash::make(request('password'))
]);
return response()->json([
'user' => $user,
'message' => 'Success'
], 200);
}
答案 0 :(得分:1)
create()方法返回模型。所以你需要稍微转换用户集合,
public function store(Request $request)
{
$this->validate($request, [
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required',
'password' => 'required'
]);
$user = User::create([
'firstname' => request('firstname'),
'lastname' => request('lastname'),
'email' => request('email'),
'password' => Hash::make(request('password'))
]);
return response()->json([
'user' => [
'id'=>$user->id,
'firstname'=>$user->firstname,
'lastname'=>$user->lastname,
'email'=>$user->email
],
'message' => 'Success'
], 200);
}