Upload image using ajax in laravel 5.8

So today we are going to upload form data with image using ajax in laravel. I expect that you know installation of laravel and basics of laravel already. If not the check this laravel guide first . Now check here how is uploading image and data will work once we are done.




Zoom page with “Control and +” Keys to see if not clear. So lets start coding .

In our view file we have form and its code is as given below



enctype=”multipart/form-data” is must in form when you planning to upload image using form.

In this form we are getting categories from database but as we need to see how image gets uploaded we will stick to that for time sake.

So lets see the route

//Adding posts using ajaxupload
      Route::post("/post/store",[
        'uses'=>'PostController@store',
        'as'=>'post.store'
      ]);

We have a controller which is dealing with insertion of data into database.

create controller using this command.

php artisan make:controller ContollerNameHere --resource

Now while making controller we are using “–resource”. Mainly it creates the necessary functions such as store(),update() etc in our controller.

As you can see our route is using “PostController” and “store” function.Below is the ajax code which is sending data to the controller without refreshing page.


 //adding posts using ajax
 
    $("#ap_submit").click(function(e){
      e.preventDefault();
      var title = $("#ptitle").val();
      var imgName = $("#pimage").val();
      var category = $("#pcategory").val();
      var tabs = $("#ptab").val();
      var content = CKEDITOR.instances["editor1"].getData();
      var authorId = $("#authorid").val();
      var newTabs = tabs.toString();
 
      var totalFormData = new FormData($("#multiselectForm")[0]);
      totalFormData.append('content',content);
      totalFormData.append('tags',newTabs);
      $.ajax({
        headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        url:"/post/store",///post/store
        type:"POST",
        data:totalFormData,
        processData: false,
        contentType: false,
        cache: false,
        success:function(data){
          $(".output_results").html(data);
        },
        error: function(data) {
          $(".output_results").html(data);
        }
      });
    });

Here in our Ajax code initially we are taking values from the form using ajax .We are stopping form to refresh the page using preventDefault method.We are getting form data using

new FormData($("#multiselectForm")[0]);
 
     //multiselectForm" is the form id

and putting it to “totalFormData” variable. We are appending authorId and newTabs into “totalFormData” variable as well.Use of “headers” is mainly for the security reasons.

Note : the url in ajax matches the route url. Which is “/post/store”.

now once we have data sent to the controller we are adding content of form into database using below given code

namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
 
use App\Category;
 
use App\Post;
 
use Validator;
 
use Session;
 
use Illuminate\Support\Facades\Input;
 
use Illuminate\Support\Facades\File;
 
    public function store(Request $request)
    {
 
        if ($request->hasFile('pimage')) {
             $post = new Post;
             $post->title = $request->Input('title');
             $post->content = $request->Input("content");
             $post->category =   $request->Input('category');
             $image = $request->file('pimage');
             $post->tabs = $request->tags;
             $post->author = $request->Input('authorid');
 
 
 
             $image_name = time().'.'.$image->getClientOriginalExtension();
             $destinationPath = public_path('/images');
             $image->move($destinationPath, $image_name);
             $post->picture='images/'.$image_name;
             $post->save();
 
             echo"Post Published Successfully";
        }
 
    }

Here is the controller code. we are not validating at this moment. We included “Post” model and the used it in our function.

Here $post->title,$post->content code is mainly that we have title and content field in our database. And we are getting input values and setting them to database fields. We are also appending “time” function to change the name of image every time user uploads it .All images are moving to “Public/images” folder.

That's it code is working you will have to change certain things in it according to your code flow.Hope this article helped you do like and comment for feedback.