Mortuza Minhaz
Mortuza Minhaz

Reputation: 21

Laravel : Update form keeping current image without input a new image isn't working

I have a form with image field, inserting all the field with image works fine

but when editing the form->to update a new image I used unlink function to remove the previous image and update with new one. The problem is if I don't upload a new image and submit the form it isn't working.

But I want to keep the current image remain if new image is not uploaded. I have tried many ways even not using unlink function but couldn't reach any solution. please help me, I really need this solution. Thanks in advance

here is my update function in controller

 public function Update(Request $request, $id){


        $PreviousPic = $request->Prev_pic;

        $data = array();
        $data['student_name'] = $request->student_name;
        $data['matric_no'] = $request->matric_no;
        $data['programme_name'] = $request->programme_name;
        $data['faculty_name'] = $request->faculty_name;
        $data['admission_year'] = $request->admission_year;
        $data['contact_no'] = $request->contact_no;

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

        if ($image){ 
            unlink($PreviousPic);
            $image_name = date('dmy_H_s_i');
            $ext = strtolower($image->getClientOriginalExtension());
            $imageFullName = $image_name.'.'.$ext;
            $uploadPath = 'media/';
            $imageURL = $uploadPath.$imageFullName;
            $success = $image->move($uploadPath,$imageFullName);

        $data['pro_pic'] = $imageURL;
        $Stdata = DB::table('students')->where('id', $id)->update($data);

        return redirect()->route('student.index')
                         ->with('success','Updated! The Student Data Updated Successfully');

        }
    }

here is my edit form image field

<div class="form-group">
  <label class="col-md-4 control-label" >Image</label>
  <div class="col-md-5 inputGroupContainer">  
  <div class="input-group">
  <span class="input-group-addon"><i class="glyphicon glyphicon-picture"></i></span>
  <div class="upload-btn-wrapper">
  <button class="btn">Upload a New Image</button>
  <input type="file" name="pro_pic" />
  </div>   
  </div>
  </div>
  </div>

<div class="form-group">
    <label class="col-md-4 control-label">Current Image </label>
    <div class="col-md-5 inputGroupContainer">
    <img src="{{ URL::to($StudentData->pro_pic)}}" height="150px" width="190px">
    <input type="hidden" name="Prev_pic" value="{{$StudentData->pro_pic}}">
    </div>
</div>

Using this I can upload new image removing the old picture. But If I keep the Upload a New Image field empty and submit the form, the form isn't submitted.

So, I want if I upload new image it works as now and if I don't upload a new image, the current image will remain & submit the form.

# I am using Laravel 7

Upvotes: 0

Views: 5504

Answers (2)

Mortuza Minhaz
Mortuza Minhaz

Reputation: 21

I have found the answer as expected

 public function Update(Request $request, $id){

        $PreviousPic = $request->Prev_pic;

        $data = array();
        $data['student_name'] = $request->student_name;
        $data['matric_no'] = $request->matric_no;
        $data['programme_name'] = $request->programme_name;
        $data['faculty_name'] = $request->faculty_name;
        $data['admission_year'] = $request->admission_year;
        $data['contact_no'] = $request->contact_no;

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

        if ($image != null){ 
            unlink($PreviousPic);
            $image_name = date('dmy_H_s_i');
            $ext = strtolower($image->getClientOriginalExtension());
            $imageFullName = $image_name.'.'.$ext;
            $uploadPath = 'media/';
            $imageURL = $uploadPath.$imageFullName;
            $success = $image->move($uploadPath,$imageFullName);

        $data['pro_pic'] = $imageURL;
        $Stdata = DB::table('students')->where('id', $id)->update($data);

        return redirect()->route('student.index')
                         ->with('success','Updated! The Student Data Updated Successfully');

        }else{
            $Stdata = DB::table('students')->where('id', $id)->update($data);

        return redirect()->route('student.index')
                         ->with('success','Updated! The Student Data Updated Successfully');
        }
    }

Just use if else statement to find the solution and it's working great.

Upvotes: 1

Shariq Shaikh
Shariq Shaikh

Reputation: 188

You need to pass the exact path of the old image from database.
You can try it with concatenation, By making two separate columns for image_name and image_path

This is my edit image code

  <div id="image" class="row" style="display: none;">
                        <div class="col-md-12">
                            <label for="text">Project Image</label>
                            <div class="form-group">
                                <input type="file" class="form-control" name="project_image"
                                value="{{ old('project_image',$currentProject->project_image) }}">
                                @if ($errors->has('project_image'))
                                <div class="text-danger">{{ $errors->first('project_image') }}</div>
                                @endif
                            </div>
                        </div>
                    </div>     

This is the div to view the previous and new image

  <div class="box box-primary">
                <div class="box-body">
                <div class="box-header text-center">    
                    <h3 class="box-title">Project Cover Image</h3>
                </div>
                <div class="row">
                    <div class="col-md-12 text-center">
                        <img class="img-responsive" src="{{  URL::asset($currentProject->project_cover_image_path.'/'.$currentProject->project_cover_image_name)}}" alt="Photo">
                        <br>
                        <a class="btn btn-primary" data-toggle="modal" data-target="#modal-project-cover">
                            Change Cover Image
                        </a>
                    </div>
                </div>
                
            </div>
        </div>  

This is the modal that actually edits the image

   {{-- Modal dialogue to edit Project Cover Image --}}
<div class="modal fade" id="modal-project-cover">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header text-center">
                <form method="POST" action="{{url('updateprojectcover', $currentProject->project_id)}}" enctype="multipart/form-data">
                    <input type="hidden" value="{{ csrf_token() }}" name="_token">
                    @if (session('error'))
                    <div class="alert alert-danger">{{ session('error') }}</div>
                    @endif
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;
                            </span>
                        </button>
                        <div class="row">
                            <div class="col-md-12">
                                <h4 for="text">Project Cover Image</h4>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group text-center">
                                    <input type="file" class="form-control" name="project_cover_image">
                                    @if ($errors->has('project_cover_image'))
                                        <div class="text-danger">{{ $errors->first('project_cover_image') }}
                                        </div>
                                    @endif
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer text-center">
                            <button type="submit" class="btn btn-primary text-center">Yes</button>
                        </div>
                </form>
            </div>
        </div>
    </div>
</div>

This is my controller to edit image

 try 
    {
        $cover_name = $request->file('project_cover_image');
        if (isset($cover_name)) 
        {
            $project_cover_image_name = $cover_name->getClientOriginalName();
            $project_cover_image_name = str_replace(" ", "_", time() . $project_cover_image_name);
            $cover_name->move(ImageUrlController::$project_cover_image_path, $project_cover_image_name);
        }
        Project::where('project_id', $project_id)
            ->update([

                'project_cover_image_path' => ImageUrlController::$project_cover_image_path,
                'project_cover_image_name' => $project_cover_image_name,
                'updated_at' => Carbon::now('PKT'),
            ]);
        return redirect()->back()->withInput();    
    } 
    catch (\Exception $exception) 
    {
        return back()->withError($exception->getMessage())->withInput();
    }

Upvotes: 0

Related Questions