首页 > 解决方案 > CRUD(更新)上传文件“在 null 上调用成员函数 getClientOriginalName()”的问题

问题描述

我想在我的管理数据中使用 Laravel 存储文件系统更新图像。但是,当我尝试上传图片时出现错误

我正在使用 Laravel 5.7

这是我的创造,创造就是成功

public function store(Request $request)
    {

        //
        $product = new \App\Product;
        $product->product_name = $request->get('product_name');
        $product->desc = $request->get('desc');
        $product->stock = $request->get('stock');
        $product->price = $request->get('price');
        $product->category = $request->get('category');



        $img = $request->file('img');

        $new_name = rand() . '.' . $img->getClientOriginalExtension();
        $img->move(public_path('img'), $new_name);
        $product->img = $new_name;
        $product->save();

        return redirect('admin')->with('success', 'Data Produk telah ditambahkan'); 
    }

这是我的更新

public function update(Request $request, $id)
    {
        //
        $product = $request->all();
        $product= \App\Product::find($id);
        $new_name = $request->file('img')->getClientOriginalName();
        $destinationPath = 'img/';
        $proses = $request->file('img')->move($destinationPath, $new_name);

        if($request->hasFile('img'))
        {
            $product = array(
                    'product_name' => $product['product_name'],
                    'desc'=> $product['desc'],
                    'stock'=> $product['stock'],
                    'price'=> $product['price'],
                    'category'=> $product['category'],
                    'img' => $new_name,
                );

            $product->save() ;
            return redirect('admin')->with('success', 'Data Produk telah ditambahkan'); 
        }


    }

在 null 上调用成员函数 getClientOriginalName()

标签: phplaravel

解决方案


我认为更新时没有附加图像文件。您可以使用我的代码作为参考。不要忘记检查更新字段中的输入字段。首先检查是否有图像文件。然后,去获取姓名,分机和其他人员。

public function update($id, Request $request)
{
    $input = $request->all();
    $product= \App\Product::find($id);

    if (empty($product)) {
        Flash::error('product not found');

        return redirect(route('products.index'));
    }
    if ($request->hasFile('product_img')) {
        $fileNameWithExt = $request->file('product_img')->getClientOriginalName();
        $filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
        $extension = $request->file('product_img')->getClientOriginalExtension();
        $new_product_img = $filename . '_' . time() . '.' . $extension;
        $path = $request->file('product_img')->move('images/products', $new_product_img);
        Storage::delete('products/'.$product->product_img);
        $input['product_img']= $new_product_img;
    }
    $product= $this->productRepository->update($input, $id);

    Flash::success('product updated successfully.');

    return redirect(route('products.index'));
}

推荐阅读