Image Upload Demo using Laravel 5.5 and Ajax

Simple profile picture upload/delete demo using Laravel 5.5, PHP, MySql, Javascript and Ajax

Run Demo


Last Updated: 3 weeks ago


Tutorial Description

Learn how to program an image file uploading script using Laravel 5.5. i use bootstrap and JavaScript for user interfacing. The server side scripting is PHP (Laravel MVC), connected to a MySQL database. Ajax is in use for server side data transmissions. I use how to change profile photo as an example. I use two methods to solve this problem, and these are;

  • 1. Changing profile photo by clicking on upload submit button on the HTML form in order to send an upload request to Route, to controller (Laravel MVC).
  • 2. Changing profile photo by clicking Ajax upload submit button in order to send an upload request to Route, to controller (Laravel MVC) JSON. The Ajax get back the response or the result after the MVC finish processing the request in JSON format and display it to the user.
  • The image uploading process ensure that user select a valid image file, and the image should not be more than 2mb.

            /****************************************************************
               *                  imageUpload.blade.php  (Route)
               ****************************************************************/
    
               /*Display  success message if the upload is successful*/
               
            @if($message = Session::get('success'))
            
    {{ $message }}
    @endif
    /*Display Error message if the upload is not successful*/ @if (count($errors) > 0)
    There was an arror with your input.
    @endif /*Display averta from*/ @foreach($averta as $photo) Last Updated: >{{ $photo->updated_at->diffForHumans() }} @endforeach
    {{ csrf_field() }}


    /**************************************************************** * web.php Route ****************************************************************/ //get current profile photo and return imageUpload page Route::get('/imageUpload','UploadimageController@get_Photo'); //upload image Route::post('/postImage','UploadimageController@UploadImage'); //Upload image with Ajax Route::post('/UpdateProfilePhoto','UploadimageController@UploadImageAjax'); /**************************************************************** * UploadimageController.php Controller ****************************************************************/ namespace App\Http\Controllers; use Validator; use Illuminate\Http\Request; use App\Models\ImageInsert; use App\Models\ImageGetimage; class UploadimageController extends Controller { //function to retrieve image from table public function get_Photo(Request $request){ $id = 1; $averta = ImageGetimage::where('id', '=', $id)->get(); //dd($averta); return view('pages.imageUpload', compact('averta')); } //function to Upload image and send back the result to imageUpload.blade.php public function UploadImage(Request $request){ request()->validate([ 'imagefile' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); $imageName = time().'.'.request()->imagefile->getClientOriginalExtension(); if(request()->imagefile->move(public_path('images'), $imageName)){ //delete old averta $old_image = $request->oldImage; if (file_exists($old_image)) { @unlink($old_image); } //update averta $id = 1; $update = ImageGetimage::find($id); $update->imagePath = isset($imageName) ? $imageName : $update->imagePath; $update ->save(); return back() ->with('success','You have successfully upload image.') ->with('image',$imageName); } } //function to Upload image using Ajax and return the result to Ajax function in imageUpload.blade.php file in JSON encode format public function UploadImageAjax(Request $request){ $validation = Validator::make($request->all(), [ 'imagefile' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); if ($validation->fails()){ return json_encode(array('error' => $validation->getMessageBag()->toArray())); // return json_encode($output); diffForHumans }else{ $imageName = time().'.'.request()->imagefile->getClientOriginalExtension(); if(request()->imagefile->move(public_path('images'), $imageName)){ //delete old averta $old_image = $request->oldImage; if (file_exists($old_image)) { @unlink($old_image); }else{ @unlink($old_image); } //update averta $id = 1; $update = ImageGetimage::find($id); $update->imagePath = isset($imageName) ? $imageName : $update->imagePath; $update ->save(); return response()->json($update); } } } } /**************************************************************** * ImageInsert.php Model ****************************************************************/ namespace App\Models; use Illuminate\Database\Eloquent\Model; class ImageInsert extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $table = 'profile_photo'; protected $fillable = [ 'imagePath' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = []; } /**************************************************************** * ImageGetimage.php Model ****************************************************************/ namespace App\Models; use Illuminate\Database\Eloquent\Model; class ImageGetimage extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $table = 'profile_photo'; protected $fillable = [ 'imagePath', 'created_at','updated_at' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = []; } /**************************************************************** * MySql table ****************************************************************/ CREATE TABLE `profile_photo` ( `id` int(11) NOT NULL, `imagePath` varchar(255) NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
            /****************************************************************
               *                 Upload image Ajax function
               ****************************************************************/
               function _(el){
        return document.getElementById(el);
    }
    
    function uploadFile(){
        var file = _("imagefile").files[0];
        var oldimg = _("oldImage").value;
       var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
    
        var formdata = new FormData();
        formdata.append("_token", CSRF_TOKEN);
        formdata.append("imagefile", file);
        formdata.append("oldImage", oldimg);
        var hr = new XMLHttpRequest();
        hr.upload.addEventListener("progress", progressHandler, false);
       
      var url = "UpdateProfilePhoto";
      hr.open("POST", url, true);
      hr.onreadystatechange = function() {
        if (hr.readyState == 4 && hr.status == 200) {
          var return_data = JSON.parse(hr.responseText);
          if(return_data.id){
                _("img_averta").src = 'images/'+return_data.imagePath;
                $('#LastUpdated').html("Last Updated: just Now");
                $('#statusimg').html("");
                 _("oldImage").value = 'images/'+return_data.imagePath;
                $('#averta_form')[0].reset();
          }else{
              $('#statusimg').html(" "+return_data.error.imagefile+"");
          }
            
        }else{
             // var return_data = JSON.parse(hr.responseText);
             // // console.log(return_data.errormessage);
          }
      }
      hr.send(formdata);
       $('#statusimg').html(" uploading.....please wait...");
    }
    function progressHandler(event){
        _("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
        var percent = (event.loaded / event.total) * 100;
        if(percent == 100){
            _("progressBar").value = Math.round(percent);
            _("status").innerHTML ="upload completed!";
            _("loaded_n_total").innerHTML = "";
        }else{
            _("progressBar").value = Math.round(percent);
            _("status").innerHTML = Math.round(percent)+"% uploading... please wait";
        }
        
    }