Categories

Thursday, November 21, 2024
#919814419350 therichposts@gmail.com
AjaxLaravel 6

How to upload multiple images in laravel 6 with ajax?

upload multiple images in laravel 6 with ajax

Hello to all, welcome to therichpost.com. In this post, I will tell you, How to upload multiple images in laravel 6 with ajax?

Post Working:

In this post, I am uploading multiple images in laravel 6 with ajax.

Here is the working code snippet and please follow carefully:

1. Here is the code , you need to add into your Blade template file:

Here is the code for upload image(HTML CODE) and you can add this code any blade template file:

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Add Media Images : </div>
                <div class="alert alert-success" style="display:none">
                    <p></p>
                </div>
                <div class="card-body">
                    <form enctype="multipart/form-data" method="post">
                        <div class="form-group">
                            <label for="image"><strong>Add Media:</strong></label>
                            <input type="file" class="form-control" id="image-upload" placeholder="Post Image" name="image_upload[]" required multiple>
                        </div>
                        <button type="button" class="btn btn-primary">Submit</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
    jQuery("document").ready(function($) {
        // Full Ajax request
        $(".btn").click(function(e) {
            // Stops the form from reloading
            e.preventDefault();

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': "{{ csrf_token() }}"
                }
            });
            let image_upload = new FormData();
            let TotalImages = $('#image-upload')[0].files.length; //Total Images
            let images = $('#image-upload')[0];
            for (let i = 0; i < TotalImages; i++) {
                image_upload.append('images' + i, images.files[i]);
            }
            image_upload.append('TotalImages', TotalImages);
            $.ajax({
                url: "{{ url('addmedia') }}",
type: 'POST', contentType: false, processData: false, data: image_upload, success: function(result) { $("div.alert").show(); $("div.alert p").text(result.message); $('#image-upload').val(""); setTimeout(function() { $("div.alert").hide(); }, 3000); // 5 secs } }); }); }); </script> @endsection

 

 

2. Here is code for route/web.php file:

This code will connect form data to controller file:

Route::post('/addmedia', 'HomeController@createmedia')->middleware('ajax');

 

3. Here is the controller file code app\Http\Controllers\HomeController.php file:

This code will save images into folder and database and I have created images table into my database :

public function createmedia(Request $request)
    {
if($request->TotalImages > 0)
         {
       
        //Loop for getting files with index like image0, image1
            for ($x = 0; $x < $request->TotalImages; $x++) {
       
            if ($request->hasFile('images'.$x)) {
             
            $file      = $request->file('images'.$x);
            $filename  = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();
            $picture   = date('His').'-'.$filename;
      
      //Save files in below folder path, that will make in public folder
            $file->move(public_path('pages/'), $picture);
      $postArray = ['image' => $picture,];
            DB::table('images')->insert($postArray);
             }
         }
     $images = DB::table('images')->orderBy('id', "desc")->get();
         return response()->json(["message" => "Media added successfully.", "images" => $images]);
     
    }
  else
  {
    return response()->json(["message" => "Media missing."]);
  }
        
    }

 

 

4. I have used Ajax Middleware and for creating ajax middleware, you have to check below link and do that functionality:

Ajax Middleware Laravel

This is it and if you have any kind of query then please do comment below.

Jassa,

Thank you

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 19, MedusaJs, Next.js, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.