Laravel使用Ajax从空值创建默认对象

时间:2017-09-30 03:12:35

标签: php jquery ajax laravel-5

我正在尝试使用Laravel中的AJAX POST方法更新我的表单,同时提交表单我收到错误:

  

从空值创建默认对象

我已经尝试过这段代码来实现我的目标。

这是我的Ajax调用

public function update(Request $request, $id)
{
    // To Update
    // $validator = Validator::make($request->all(), [
    $this->validate($request,[
        'design_no'=>'required',
        'design_image'=>'image|nullable|max:1999'
    ]);
            // Handle file Upload
     if ($request->hasFile('design_image')) {
        // Get filename with image 
            $filenameWithex=$request->file('design_image');
        // Get just file name
             $filename=$_FILES['design_image']['name'];
            // $filename=pathinfo($filenameWithex,PATHINFO_FILENAME);
        // Get just ex 
            // $extension=pathinfo($filenameWithex,PATHINFO_EXTENSION);
        // File Name To Store
            $fileNameToStore=$filename;
        // Upload Image
            $path=$request->file('design_image')->storeAs('public/images',$fileNameToStore);
    }else{
        $fileNameToStore='noimage.jpg';
    }
    $design=design::find($id);
    $design->design_no=$request->input('design_no');
    $design->desg_1=$request->input('desg_1');
    $design->design_image=$fileNameToStore;
    $design->desg_2=$request->input('desg_2');
    $design->desg_3=$request->input('desg_3');
    $design->desg_4=$request->input('desg_4');
    $design->desg_5=$request->input('desg_5');
    $design->desg_6=$request->input('desg_6');    
    $design->save();
    return '1';
}  

这就是我在Laravel Controller中为完成目标所做的工作。

这是我的Laravel控制器页面:

# match digits in the regex
echo preg_replace_callback('/[\d]+/',function($v){
    # reverse string
    return strrev($v[0]);
},$str);

1 个答案:

答案 0 :(得分:1)

问题在于$design=design::find($id);

我认为$design在单词$design=design::find($id);中为null,在这里返回null?

如果需要,你需要检查

$design=design::find($id);
    if($design){
            $design->desg_1=$request->input('desg_1');
            $design->design_image=$fileNameToStore;
            $design->desg_2=$request->input('desg_2');
            $design->desg_3=$request->input('desg_3');
            $design->desg_4=$request->input('desg_4');
            $design->desg_5=$request->input('desg_5');
            $design->desg_6=$request->input('desg_6'); 
    }

如果你想更新你的记录,那么我会建议你这样简单的更新查询方法

design::where('design_no',$id)->update([
           'desg_1' => $request->input('desg_1'),
            'design_image'=> $fileNameToStore,
            'desg_2' => $request->input('desg_2'),
            'desg_3' => $request->input('desg_3'),
            'desg_4' => $request->input('desg_4'),
            'desg_5' => $request->input('desg_5'),
            'desg_6' => $request->input('desg_6') 
]);

希望这能解决您的问题:)