我是拉拉维尔的新手。我一直在尝试将图像保存到数据库中。这是我尝试用于存储图像的控制器方法
public function store(Request $request){
//validation for form
$validate= $request->validate([
'name' => 'required|min:2|max:140',
'position' => 'required|min:2|max:140',
'salary' => 'required|min:2|max:140',
'joining_date' => ''
]);
//saving form
if($validate){
$employee=new Employee;
$employee->name =$request->input('name');
$employee->company_name =$request->input('company_name');
$employee->position =$request->input('position');
$employee->salary =$request->input('salary');
$employee->joining_date =$request->input('joining_date');
$employee->user_id= auth()->user()->id;
//image saveing method
if($request->hasFile('image')){
$image= $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
Employee::make($image)->resize(300, 300)->save( public_path('/employee/images/' . $filename ) );
$employee->image= $filename;
}else{
return $request;
$employee->image= '';
};
$employee->save();
//redirecting to Employee list
return redirect('/employee/details')->with('success','Employee Added');
}
我可以在没有图像的情况下保存表单并将其重定向到详细信息页面。 但是现在当我尝试使用图像时,它不是保存它并重定向到详细信息路由,而是将我返回到数据库行数组,如下所示:
{
"_token": "FPHm9AKuEbRlqQnSgHhjPnCEKidi2xr0usgp7RoW",
"name": "askfjlk",
"company_name": "laksjsflkj",
"position": "lkasjfkl",
"salary": "35454",
"joining_date": "4654-05-06",
"image": "testing.png"
}
我在这里做错了什么?请帮帮我这个新手。
您返回$request对象,Laravel会自动进行JSON响应。
if ($request->hasFile('image')){
// image storing logic which obviously is never started because expression above is false
} else {
return $request; // There is your problem
$employee->image= '';
};
您需要检查为什么在$request->hasFile('image'(上出现错误。
另外,一个提示,因为您是Laravel的新手:
// When you are accessing to $request object you can use dynamic propertes:
$employee->company_name = $request->input('company_name');
// is the same as
$employee->company_name = $request->company_name;
你可以在那里检查它:Laravel文档在部分:通过动态属性检索输入