我正在尝试将图片提交到数据库中,但我一直收到此错误:Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, null given, called in C:\xampp\htdocs\Evaluation\app\Http\Controllers\ImageController.php on line 24.
我在StackOverflow中检查了其他问题,大多数时候他们说这是保存部分的错误,他们放了这样的东西,$post
但是我已经检查过并且没有任何问题。这种关系似乎也没有任何问题,但为什么它仍然不起作用?当我上传图片时,错误也会返回null。 null在这里的部分返回,$UserImage = $request->input('UserImage');
那么我的问题可能在image1.blade.php
吗?
ImageController:
public function test(personal_info $user){
return view('image1',compact('user'));
}
public function test1(Request $request){
$UserImage = new Image;
$personal_info = new personal_info;
$UserImage = $request->input('UserImage');
$id = $request->user_id;
$id = personal_info::find($id);
$id->Images()->save($UserImage);
return redirect('/summary');
}
image1.blade.php(我提交表单的地方)
<form class="form-horizontal" method="post" action="{{ url('/Upload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{$user->id}}">
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="UserImage">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2" style="padding-left: 30px">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
Image.php:
public function personal_infos() {
return $this->belongsTo('App\personal_info', 'user_id', 'id');
}
personal_info.php:
public function Images() {
return $this->hasOne('App\Image','user_id');
}
答案 0 :(得分:2)
public function test1(Request $request)
{
// make new instance of Image Model
$imageModel = new Image;
// find personal_info Model by id
$personal_info = personal_info::findOrFail($request->input('user_id'));
// UploadedFile
$image = $request->file('UserImage');
// get the file contents?
$imageModel->content = ...
// save the relationships, pass a model instance to `save`
$personal_info->Images()->save($imageModel);
return redirect('/summary');
}