我无法在Laravel 7的数据库中存储信息



我在MySQL数据库中存储信息时遇到了问题,我试图更改将信息存储到DB中的方法,但仍然存在同样的问题。此外,我需要你的帮助来解决这个问题

PostController

<?php 
public function store(){
$inputs= request()->validate([
'title'=>'required|min:8|max:100',
'post_image'=>'file',
'body'=>'required'
]);
if (request('post_image')){
$inputs['post_image']=request('post_image')->store('images');
}
auth()->user()->posts()->create($inputs);
return back();
}

后期模型

<?php
class Post extends Model
{
//
protected $guarded =[];
public function user(){
return $this->belongsTo(User::class);
}
public function getPostImageAttribute($value){
return asset($value);
}
}

表单

<form action="{{route('post.store')}}" method="post" enctype="multipart/form-data">
@csrf
<div class="form-group">
<lable for="title">Title</lable>
<input type="text" name="title" class="form-control" placeholder="Enter title">
</div>
<div class="form-group">
<lable for="file">File</lable>
<input type="file" name="post_image" class="form-control-file" id="post_image" placeholder="Upload your image">
</div>
<div class="form-group">
<lable for="exampleInputEmail"></lable>
<textarea  name="body" cols="30" rows="10" class="form-control"></textarea>
</div>
<button type="submit" class="btn btn-primary"> Submit</button>
</form>

我感谢你帮助我的努力,并提前表示感谢。

要获取请求对象的文件,可以通过file((方法访问它。为什么你不使用方法注入的请求

//use IlluminateHttpRequest; - import the use statement at top
public function store(Request $request){
$inputs= $request->validate([
'title'=>'required|min:8|max:100',
//'post_image'=>'file',
'body'=>'required'
]);
if ($request->hasFile('post_image') && $request->file('post_image')->isValid()){
$inputs['post_image'] = $request->file('post_image')->store('images');
}
auth()->user()->posts()->create($inputs);
return back();
}

最新更新