Search code examples
phplaravelintervention

Uploading Images in laravel using Intervention


i am tring to upload images in laravel 5.6 using intervention and its working perfectly, the only problem is the path it is storing on the database is like /var/www/Laravel/project/public/uploads/students/1534413021.jpg and what i want is for it to store it as /uploads/students/1534413021.jpg. Here is my form

    <form class="form-horizontal" method="post" action="{{ route('student.Avatar.submit',$student->id)}}" enctype="multipart/form-data">
                  {{ csrf_field() }}
                  <div class="form-group ">
                    <label class="col-sm-2 control-label">Select Image To Upload:</label>
                    <div class="col-sm-10 {{ $errors->has('avatar') ? ' has-error' : '' }}">
                      <input type="file" name="avatar" value="{{ old('avatar') }}" class="form-control rounded">
                      @if ($errors->has('avatar'))
                      <span class="help-block">
                        <strong>{{ $errors->first('avatar') }}</strong>
                      </span>
                      @endif
                    </div>
                  </div>
                  <div class="form-group">
                    <div class="col-sm-4 col-sm-offset-2">
                      <button type="submit" class="btn btn-primary btn-rounded btn-block">Save changes</button>
                    </div>
                  </div>
                </form>

and here is the controller

      public function uploadAvatar(Request $request, Student $student)
  {
    $validatedData = $request->validate([
      'avatar' => 'required | mimes:jpeg,jpg,png,bmb,gif,svg',
    ]);

    if ($request->hasFile('avatar')) {
      $image = $request->file('avatar');
      $fileName = time() . '.' . $image->getClientOriginalExtension();
      $location = public_path('uploads/students/'.$fileName);
      Image::make($image)->resize(800,400)->save($location);

      $studentUpdate = Student::where('id',$student->id)
      ->update([
        'avatar'=>$location,
      ]);
      if ($studentUpdate) {
        return redirect()->route('students.profile',$student->id)->with('success','Student Profile Created Successfully');
      }else{
          return back()->withInput()->with('errors','Error adding new parent.');
      }

    }
    return back()->withInput()->with('errors','PLease Select An Image.');
  }

Solution

  • change your path while saving like this:

    $location = public_path('uploads/students/'.$fileName); 
    

    To this:

    $location = 'uploads/students/'.$fileName;
    

    It will automatically go to public/$location and save the file and you will have only required string in database;