0

我是 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"
}

我在这里做错了什么?请帮我解决这个新手。

4

1 回答 1

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')上得到错误

另外,一个提示,因为你是 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 文档部分中的:通过动态属性检索输入

于 2019-12-23T21:49:12.017 回答