Laravel PHP : Upload image with validation using jquery ajax form plugin

Laravel PHP : Upload image with validation using jquery ajax form plugin

In this post we will give you information about Laravel PHP : Upload image with validation using jquery ajax form plugin. Hear we will give you detail about Laravel PHP : Upload image with validation using jquery ajax form pluginAnd how to use it also give you demo for it if it is necessary.

In this post, I will let you know how to upload image file on server using jquery form plugin in Laravel PHP Framework.

In our last post, I have explained How to upload image with validation in Laravel.

Uploading image using jquery is in demand in most applications where you need to change your profile image.

This will be helpful because uploading image file using ajax won’t reload the entire webpage.

Laravel provide different type of validation rules for image file, you can set the max file size, their mime type etc.

In this example, We will use ajax to upload image without page refresh and get preview of uploaded image.


Step 1 : Add routes

In this first step, Add following routes in your routes/web.php for ajax upload image.

  1. Route::get('get-image','ImageController@getImage');
  2. Route::post('ajax-upload-image',['as'=>'ajax.upload-image','uses'=>'ImageController@ajaxUploadImage']);
Route::get('get-image','ImageController@getImage');
Route::post('ajax-upload-image', ['as'=>'ajax.upload-image','uses'=>'ImageController@ajaxUploadImage']);


Step 2 : Create ImageController

In this step, we will create ImageController in following path app/Http/Controllers/ImageController.


app/Http/Controllers/ImageController.php

  1. <?php
  2. namespace AppHttpControllers;
  3. use IlluminateHttpRequest;
  4. class ImageController extends Controller
  5. {
  6.     public functiongetImage(){
  7.         returnview('ajaxUploadImage');
  8.     }
  9.     public functionajaxUploadImage(Request $request){
  10.         $this->validate($request,[
  11.      'image'=>'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
  12.     ]);
  13. $image=time().'.'.$request->image->getClientOriginalExtension();
  14. $request->image->move(public_path('images'),$image);
  15. $url='images/'.$image;
  16. returnresponse()->json(['url'=>$url]);
  17.     }
  18. }
<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class ImageController extends Controller
{
  public function getImage(){
    return view('ajaxUploadImage');
  }

  public function ajaxUploadImage(Request $request){
    $this->validate($request, [
          'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        $image = time().'.'.$request->image->getClientOriginalExtension();
        $request->image->move(public_path('images'), $image);
        $url='images/'.$image;
        return response()->json(['url'=>$url]);

  }

}


Step 3 : Create View “ajaxUploadImage.blade.php” File

In this step, we will manage layouts and design form to upload files to send to the server.

To have jQuery form plugin we will include following library :

  • bootstrap.min.css
  • jquery.min.js
  • jquery.form.min.js

resources/views/ajaxUploadImage.blade.php

  1. <!DOCTYPEhtml>
  2. <html>
  3. <head>
  4.     <title>Laravel 5 - Ajax upload image to server without refresh the page with preview</title>
  5.     <linkrel="stylesheet"type="text/css"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  6.     <scriptsrc="http://code.jquery.com/jquery-3.2.1.min.js"></script>
  7.     <scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.1/jquery.form.min.js"></script>
  8. </head>
  9. <body>
  10. <divclass="container">
  11. <h1>Laravel 5 - jQuery ajax upload image with example</h1>
  12. {!! Form::open(['route'=>'ajax.upload-image','files'=>'true']) !!}
  13.     <divclass="alert alert-danger error-msg"style="display:none">
  14. <ul></ul>
  15. </div>
  16. <divclass="preview-uploaded-image">
  17. </div>
  18.     <divclass="form-group">
  19. <label>Image:</label>
  20. <inputtype="file"name="image"class="form-control">
  21. </div>
  22. <divclass="form-group">
  23. <buttonclass="btn btn-primary upload-image"type="submit">Upload Image</button>
  24. </div>
  25. {!! Form::close() !!}
  26. </div>
  27. <scripttype="text/javascript">
  28. $("body").on("click",".upload-image",function(e){
  29. $(this).parents("form").ajaxForm({
  30. complete: function(response)
  31. {
  32. if($.isEmptyObject(response.responseJSON.image)){
  33. $('.preview-uploaded-image').html('<imgsrc="'+response.responseJSON.url+'">');
  34. }else{
  35. var msg=response.responseJSON.image;
  36. $(".error-msg").find("ul").html('');
  37. $(".error-msg").css('display','block');
  38. $.each( msg, function( key, value ) {
  39. $(".error-msg").find("ul").append('<li>'+value+'</li>');
  40. });
  41. }
  42. }
  43. });
  44. });
  45. </script>
  46. </body>
  47. </html>
<!DOCTYPE html>
<html>
<head>
  <title>Laravel 5 - Ajax upload image to server without refresh the page with preview</title>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.1/jquery.form.min.js"></script>
</head>
<body>

<div >
  <h1>Laravel 5 - jQuery ajax upload image with example</h1>

  {!! Form::open(['route'=>'ajax.upload-image','files'=>'true']) !!}
    <div  style="display:none">
        <ul></ul>
    </div>

    <div >
    </div>

    <div >
      <label>Image:</label>
      <input type="file" name="image" >
    </div>

    <div >
      <button  type="submit">Upload Image</button>
    </div>
  {!! Form::close() !!}

</div>

<script type="text/javascript">
  $("body").on("click",".upload-image",function(e){
    $(this).parents("form").ajaxForm({ 
      complete: function(response) 
      {
        if($.isEmptyObject(response.responseJSON.image)){
          $('.preview-uploaded-image').html('<img src="'+response.responseJSON.url+'">');
        }else{
          var msg=response.responseJSON.image;
          $(".error-msg").find("ul").html('');
          $(".error-msg").css('display','block');
          $.each( msg, function( key, value ) {
            $(".error-msg").find("ul").append('<li>'+value+'</li>');
          });
        }
      }
    });
  });

</script>

</body>
</html>
Show Demo

Hope this code and post will helped you for implement Laravel PHP : Upload image with validation using jquery ajax form plugin. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

9  +  1  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US