【问题标题】:Creating default object from empty value "error in laravel"从空值“laravel 中的错误”创建默认对象
【发布时间】:2019-01-10 19:06:36
【问题描述】:

您好,我正在更新电子商务网站的产品形式,但是当我尝试编辑详细信息时,它显示错误“未定义的变量:文件名”并且错误行是:

 Product::where(['id'=>$id])->
 update(['product_name'=>$data['product_name'],
 'product_code'=>$data['product_ code'],
 'product_color'=>$data['product_color'],
 'description'=>$data['description'],
 'price'=>$data['price'],'image'=>$fileName]);
    return redirect()->back()->with('flash_message_success','Product 
  updated successfully!');

或者当我尝试更新图像时,它的错误是:“从空值创建默认对象”,或者错误行是:

$product->image = $filename;

这是 ProductsController 的代码:

 public function editProduct(Request $request, $id=null){

  if($request->isMethod('post')){
    $data = $request->all();
    //echo "<pre>"; print_r($data); die;


    if($request->hasFile('image')){
      $image_tmp = Input::file('image');
      if($image_tmp->isValid()){
        $extension = $image_tmp->getClientOriginalExtension();
        $filename = rand(111,99999).'.'.$extension;
        $large_image_path = 
  'images/backend_images/products/large/'.$filename;
        $medium_image_path = 
  'images/backend_images/products/medium/'.$filename;
        $small_image_path = 
  'images/backend_images/products/small/'.$filename;
        // Resize Images
        Image::make($image_tmp)->save($large_image_path);
        Image::make($image_tmp)->resize(600,600)->save($medium_image_path);
        Image::make($image_tmp)->resize(300,300)->save($small_image_path);

        // Store image name in products table
        $product->image = $filename;
       }
      }

     if(empty($data['description'])){
          $data['description'] = '';
        }


     Product::where(['id'=>$id])- 
      >update(['product_name'=>$data['product_name'],
       'product_code'=>$data['product_code'],
       'product_color'=>$data['product_color'],
       'description'=>$data['description'],
       'price'=>$data['price'],'image'=>$fileName]);
       return redirect()->back()->with('flash_message_success','Product 
        updated successfully!');
       }

    //Get product details
    $productDetails = Product::where(['id'=>$id])->first();

     return view('admin.products.edit_product')- 
      >with(compact('productDetails'));
    }

【问题讨论】:

  • 您没有在任何地方定义$product,而是立即尝试通过$product-&gt;image = $filename在您的代码中使用它
  • @TimLewis 你愿意告诉我如何解决它
  • 在您尝试设置属性之前将$product定义为...例如$product = ...;然后$product-&gt;image ...
  • $product = $filename;但仍然是同样的错误

标签: laravel laravel-5 eloquent


【解决方案1】:

“未定义变量:文件名”

您的变量中有错字。将$fileName 更改为$filename

【讨论】:

    【解决方案2】:

    我猜你需要做这样的事情

    $product=new Product();
    $product->image = $filename;
    

    还有你在代码中哪里定义了 $fileName?

    【讨论】:

    • 请问是什么错误,如果可能的话,贴截图
    猜你喜欢
    • 2017-01-22
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 2018-07-18
    相关资源
    最近更新 更多