我是Laravel的新手。我一直试图将图像保存到数据库。这是我尝试存储图像的控制器方法
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"
}
我在这里做错了什么?请帮我解决这个问题。
答案 0 :(得分:0)
您将返回 $ 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')上出现 false 。
还有一个提示,因为您是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 docs在“通过动态属性检索输入”部分中