我有一个简单的表格:
<form method="post" action="{{ route('company.store') }}">
Logo: <br>
<input name="logo" type="file"><br>
在我的控制器中,我尝试使用保存图片
$file = $request->file('logo')->store('avatars');
但是我有错误
"Call to a member function store() on null"
dd($request->file('logo');
显示'null'
如何访问文件进行保存?
答案 0 :(得分:4)
要上传文件,您需要在打开表单标签的过程中添加enctype="multipart/form-data"
:
<form method="post" action="{{ route('company.store') }}" enctype="multipart/form-data">
如果不包括它,那么只会提交文件名,并且会导致
$request->file('logo')
返回null
,因为它不是文件,而是字符串。
答案 1 :(得分:1)
上传文件需要一个enctype =“ multipart / form-data”
<form action="{{ route('company.store') }}" method="post" enctype="multipart/form-data"
class="form-material">
{{csrf_field()}}
<div class="form-body">
<h3 class="card-title">upload image</h3>
<div class="form-group">
<label class="control-label">image 1</label>
<input type="file" name="image_path" class="form-control">
</div>
</div>
</form>
Your Controller should look like this .
public function store(Request $request)
{
$this->validate($request,['image_path'=> 'required|image']);
$company = new Company();
if($request->hasFile('image_path'))
{
$company->image_path= $request->file('image_path')->store('company','public');
}
$company->save();
return back()->with('success', 'Done!');
}