Alex Bene
Alex Bene

Reputation: 243

How to fix "Undefined variable: img_name" error in laravel

i have a project on laravel 5.8; i have this error; please help me : Undefined variable: img_name

this my html code :

    <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>

My Controller :

    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');

    }

I have this error, i dont understand, if you can explain me please; thank you Undefined variable: img_name

Upvotes: 0

Views: 147

Answers (1)

Leonardo Rossi
Leonardo Rossi

Reputation: 3022

If $request->hasFile('p_image') is false you don't define the $img_name variable.

But you always execute the code

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

which is wrong. Change your code to

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
    ]);
}

Upvotes: 1

Related Questions