如何修复Laravel中的“未定义的变量:img_name”错误

时间:2019-05-29 14:46:35

标签: laravel

我在laravel 5.8上有一个项目;我有这个错误;请帮我 : 未定义的变量:img_name

这是我的html代码:

    <div class="input-group control-group increment" >
      <input id="p_image" type="file" name="p_image" class="form-control">
      <div class="input-group-btn"> 
        <button class="btn btn-success" type="button"><i class="glyphicon glyphicon-plus"></i>Add</button>
      </div>
    </div>
    <div class="clone hide">
      <div class="control-group input-group" style="margin-top:10px">
        <input id="p_image" type="file" name="p_image" class="form-control">
        <div class="input-group-btn"> 
          <button class="btn btn-danger" type="button"><i class="glyphicon glyphicon-remove"></i> Remove</button>
        </div>
      </div>
    </div>

我的控制器:

    public function store(Request $request)
    {
        $this->validate(request(), [

            'p_image' => 'image|mimes:jpg,jpeg,png|max:2048'

        ]);


        if($request->hasFile('p_image')){
            $img_name = time() . '.' . $request->p_image->getClientOriginalExtension();
        }

         // awi sora s lfolder public/uploads
        if($request->hasFile('p_image')){
            $request->p_image->move(public_path('upload'), $img_name);
        }

        Image::create([
            'p_image' => $img_name,
            'post_id' => $post->id

        ]);

        return redirect('/posts');

    }

我有这个错误,我不明白,请您解释一下;谢谢 未定义的变量:img_name

1 个答案:

答案 0 :(得分:1)

如果$request->hasFile('p_image')false,则无需定义$img_name变量。

但是您总是执行代码

Image::create([
    'p_image' => $img_name,
    'post_id' => $post->id
]);

这是错误的。将您的代码更改为

if($request->hasFile('p_image')){
    $img_name = time() . '.' . $request->p_image->getClientOriginalExtension();
    $request->p_image->move(public_path('upload'), $img_name);
    Image::create([
        'p_image' => $img_name,
        'post_id' => $post->id
    ]);
}