【发布时间】:2021-05-11 21:41:50
【问题描述】:
我正在使用 Laravel 8 开发我的项目,在这个项目中,我有一个用于添加新用户和上传他们的个人资料图片的页面。
现在在 Controller 的 store(),我编写了这个代码:
public function store(Request $request)
{
$user = new User();
$validate_data = Validator::make(request()->all(),[
'name' => 'required|min:4',
'email' => 'required|email|unique:users',
'status' => 'required',
'role' => 'required',
'password' => 'required|min:6',
])->validated();
if($file = $request->file('avatar')){
$name = time() . $file->getClientOriginalName();
$file->move('images', $name);
$photo = new Photo();
$photo->name = $file->getClientOriginalName();
$photo->path = $name;
$photo->user_id = Auth::id();
$photo->save();
$user->photo_id = $photo->id; //Adding photo id to the new user at users table
}
$creation = User::create([
'name' => $validate_data['name'],
'email' => $validate_data['email'],
'status' => $validate_data['status'],
'role_id' => $validate_data['role'],
'password' => bcrypt($validate_data['password'])
]);
if($creation){
alert()->success('User was added', 'Success');
return redirect('/admin/users/');
} else {
return '1003';
}
}
它工作正常且正确,并将新用户添加到users 表并将照片添加到photos 表。
但是应该将photo_id 添加到users 表的这一行不起作用,并且新用户的photo_id 不知何故为空!
User 和 Photo Models 之间的关系是这样的:
User.php:
public function photos()
{
return $this->hasMany(Photo::class);
}
Photo.php:
public function user()
{
return $this->belongsTo(User::class);
}
我还在用户模型中添加了photo_id 作为fillbale。
那么这里出了什么问题?我该如何解决这个问题?
我非常感谢您对此提出任何想法或建议...
提前致谢。
这里是迁移,如果你想看看:
create_photos_table表:
public function up()
{
Schema::create('photos', function (Blueprint $table) {
$table->increments('id');
$table->string('path');
$table->string('name');
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
add_avatar_to_users_table:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->integer('photo_id')->unsigned()->nullable();
});
}
【问题讨论】: