Skumar
Skumar

Reputation: 520

Cannot upload image path to database in laravel 7

I am trying to upload user pic to database using the Storage facade. I used this php artisan storage:link to create a symbolic link and all, but the file path is neither uploaded to database, nor am I getting any kind of error

Here are my codes

Controller

public function edituser_pic(Request $request){
  if(Auth::check()){
          $u_id = $request->id; 
          
         if($request->hasFile('mypic')){
              $path = Storage::disk('public')->putFile('profile_image',$request->mypic);

              $profilepic = $path;
         }else{
            $profilepic='';
         }
         DB::table('users')->where('id',$u_id)->update(['profilepic'=>$profilepic]);

         return response()->json([
            'success'=>true,
            'path'=>$profilepic,
         ]);
   }
}

In Blade (while trying to access the image)

<img class="img-fluid img-profile rounded-circle mx-auto mb-2" src="{{url('storage/'.Auth::user()->profilepic)}}" alt="AB" />

Upload form code

<h2>Edit Profile Picture</h2>
        <form id='profilepic' autocomplete="off" enctype="multipart/form-data">
          @csrf
          <input type="hidden" name="_token" id="csrf" value="{{Session::token()}}">
          <input type="hidden" name="id" id='id' value="{{Auth::user()->id}}">
          <label>Select an image to upload : <br><br>(only jpg, jpeg,png files are allowed)</label><br><br>
          <input type="file" name="mypic" id="mypic" class="text-white">
          <div class="error text-danger"></div>
          <button type="submit" class="buttons bttn" id='editprofilepic'>Upload Image</button>
          <button type="button" class="cancelb">Cancel</button>
        </form>
<script>
//see below
</script>

Script

 $.validator.addMethod('filesize', function (value, element, param) {
    return this.optional(element) || (element.files[0].size <= param * 1000000)
}, 'File size must be less than {0} MB');

    jQuery.validator.addMethod("extension", function(value, element, param) {
  param = typeof param === "string" ? param.replace(/,/g, '|') : "png|jpe?g|gif";
  return this.optional(element) || value.match(new RegExp(".(" + param + ")$", "i"))
}, "Please enter a value with a valid extension.");
   var v = $('#profilepic').validate({
       rules:{
        mypic:{
          required:true,
          extension: "jpg|jpeg|png",
          filesize:true,
        },
      },
      messages:{
        mypic:{
           required:"Please select an image file. If you dont't want a profile pic, please use the cancel button",
           extension:"Image files with the following extensions are allowed - .jpg, .jpeg, .png",
           filesize: "Maximum size of the image - 5 MB",
        },
      },
        errorPlacement: function (error, element) {
            element.each(function () {
                $(this).next("div .error").html(error);
            });
        },
    }); 
    
    $('#editprofilepic').click(function(e){
        e.preventDefault();
        if($('#profilepic').valid()){
         $.ajax({
              url: 'edituser_pic',
              method:'post',
              cache: false,
              processData:true,   //Required
              contentType: 'application/x-www-form-urlencoded',
              data:{
                   '_token' :$('#csrf').val(),
                   'id'     : $('#id').val(),
                   'mypic'  : $('#mypic').val(),
              },
              success:function e(response){
                console.log(response.path);
                 if(response.success== true){
                  Command: toastr["success"]("You will now be redirected..","Profile Picture updated.")
                            toastr.options = {
                              "closeButton": false,
                              "debug": false,
                              "newestOnTop": false,
                              "progressBar": true,
                              "positionClass": "toast-top-full-width",
                              "preventDuplicates": false,
                              "onclick": null,
                              "showDuration": "300",
                              "hideDuration": "1000",
                              "timeOut": "5000",
                              "extendedTimeOut": "1000",
                              "showEasing": "swing",
                              "hideEasing": "linear",
                              "showMethod": "fadeIn",
                              "hideMethod": "fadeOut",
                              
                            }
                           setTimeout(function(){ location.replace('http://localhost/LaraTest/public/profile');},5500); 
                  }else{
                     Command: toastr["warning"]("Some error","Please try later")
                            toastr.options = {
                              "closeButton": false,
                              "debug": false,
                              "newestOnTop": false,
                              "progressBar": true,
                              "positionClass": "toast-top-full-width",
                              "preventDuplicates": false,
                              "onclick": null,
                              "showDuration": "300",
                              "hideDuration": "1000",
                              "timeOut": "5000",
                              "extendedTimeOut": "1000",
                              "showEasing": "swing",
                              "hideEasing": "linear",
                              "showMethod": "fadeIn",
                              "hideMethod": "fadeOut",
                              
                            }
                            noofsubmits = 0;

                  }
              },
              error:function es(response){
                swal({
                  title:"Some error",
                  text:"Please try later",
                  icon:"warning",
                  button:true
                });
               
              }

          }); //ajax ends
        
      }
    });

Upvotes: 0

Views: 176

Answers (1)

pc_fuel
pc_fuel

Reputation: 786

From your last comment to @Syazany, it seems like the the file is not being sent properly via ajax request to the controller. You can do either of the two things.

Option 1 ->

Post the form using the Submit button and NOT using Ajax. This should send the file name, temporary path to the Controller. If using this method, don't forget to use method="post" and action="somewhere.php" in the form tag.

Option 2 ->

Use FormData as below to send the form data using ajax -

var formData = new FormData(document.getElementById("profilepic"));

$.ajax({
        url: 'edituser_pic',
        method:'post',
        cache: false,
        processData:false,   //Required
        contentType: false,  //Required
        data:formData,
        success: function(){
         //do something for success            
         },
        error: function(){
         //do something for error
          },

});

P.S-

processData:false,   //Required
contentType: false,  //Required

are necessary if using FormData

Upvotes: 1

Related Questions