Jason Paddle
Jason Paddle

Reputation: 1103

Preloading image in edit form

I have edit form which is populated from database when I go to update page. Everything works fine except the image part. If I don't submit new image it deletes old one too.

This is my controller

public function update( ItemRequest $request){

    $item = Item::find( $request['id'] );
    $filename=null;

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

    if($request->hasFile('image'))
    {
        if($image->isValid()){
            $extension = $image->getClientOriginalExtension();
            $uploadPath = public_path(). '/uploads';
            $filename = rand(111,999). '.'. $extension;
            $image->move($uploadPath, $filename);   
        }
    }


    $item->title = $request['title'];
    $item->category_id = $request['category_id'];
    $item->price = $request['price'];
    $item->description = $request['description'];
    $item->image = $filename? $filename: $item->image;
    $item->image = $filename;

    if($item->save()){

        if(!is_null($filename)){
            $item_image = new Item_Images;
            $item_image->image = $filename;
            $item_image->item_id = $item->id;
            $item_image->published = 1;
            $item_image->save();
        }

        $request->session()->flash('alert-success','Item updated successfully.');
    } else
        $request->session()->flash('alert-error','Can not update item now. Plese tyr again!!.');      

    return redirect()->route('products');
}

And the corresponded fields for image on the form

 @if( $item['image'] )  
       <div class="form-group">
       {!! Form::label('inputImage', 'Existing Image', array('class'=> 'col-sm-2 control-label')) !!}
           <div class="col-sm-10">
                <img src="{!!asset('/uploads/'. $item['image'] )!!}" />                   
           </div>
        </div>
 @endif

 <div class="form-group">
       {!! Form::label('inputImage', 'Image', array('class'=> 'col-sm-2 control-label')) !!}
          <div class="col-sm-10">
              {!! Form::file('image', ['class'=>'form-control', 'id'=>'inputImage']) !!}                      
          </div>
 </div>

First I check if there is image in database and if there is it is shown on the page. There there is the file field.

So is it possible to load as a value the current image in file field of form? Or this must be done in controller logic somehow?

Upvotes: 2

Views: 595

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

Remove this line to fix the problem:

$item->image = $filename;

By doing this, you'll set image as null if no image was uploaded.

Upvotes: 1

Related Questions