Laravel 11 Ajax Image Upload Example Tutorial

Ajax can perform actions on web pages without refreshing the web page, you can easily upload images in Laravel 11 application without refreshing the web page using Ajax.

In this guide, we will show you step-by-step how to upload an image without refreshing the web page using Ajax in Laravel 11 applications.

Upload Image in Laravel 11 using Ajax

Here are some steps to upload images without page refresh using Ajax in laravel 11 applications:

Step 1 – Download the New Laravel Application

Run the composer create-project --prefer-dist laravel/laravel myBlog command on cmd to download and set up new laravel application on your system:

composer create-project --prefer-dist laravel/laravel myBlog

Step 2 – Create Routes to Handle Ajax Requests

Now open web.php from the routes folder, and create two routes in it that will handle Ajax requests like the following:

use App\Http\Controllers\AjaxUploadController;

Route::get('form', [AjaxUploadController::class, 'index']);
Route::post('upload', [AjaxUploadController::class, 'uploadImageByAjax']);

Step 3 – Create Controller File

Now create a controller file using php artisan make:controller AjaxUploadController command on cmd:

php artisan make:controller AjaxUploadController

Now open the AjaxUploadController.php file from the app/http/controller folder, and create two methods in it that will handle file uploading from Ajax requests, like the following:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AjaxUploadController extends Controller
{
     public function index()
    {
        return view('form');
    }

    public function uploadImageByAjax(Request $request)
    {

        $validatedData = $request->validate([
         'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',

        ]);

        $name = $request->file('image')->getClientOriginalName();

        $path = $request->file('image')->store('public/images');


        return response()->json('image has been uploaded');

    }
}

Step 4 – Create Image Upload Form

Go to the resources/views folder and create a file here named form.blade.php, and create a form to send the image to the server or controller via Ajax, like the following:

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 11 Ajax Image Upload Example - Tutsmake.com</title>

  <meta name="csrf-token" content="{{ csrf_token() }}">

  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">

</head>
<body>

<div class="container mt-4">

  <h2 class="text-center">Laravel 11 Ajax Image Upload Example - Tutsmake.com</h2>

      <form method="POST" enctype="multipart/form-data" id="image-upload" action="javascript:void(0)" >

          <div class="row" style="margin-left: 19%">

              <div class="col-md-12 mb-2">
                  <div class="form-group">
                      <input type="file" name="image" placeholder="Choose image" id="image">
                  </div>
              </div>

              <div class="col-md-12 mb-2">
                  <button type="submit" class="btn btn-primary" id="submit">Submit</button>
              </div>
          </div>
      </form>
</div>


</div>
</body>
</html>

Now Write AJAX code in the form.blade.php file, with the help of which the image will be sent to the server for uploading without refreshing the web page, like this:

   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function (e) {

   $.ajaxSetup({
       headers: {
           'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
   });


   $('#image-upload').submit(function(e) {

     e.preventDefault();

     var formData = new FormData(this);

     $('#submit').text('Please wait').attr('disabled', 'disabled');

     $.ajax({
        type:'POST',
        url: "{{ url('upload')}}",
        data: formData,
        cache:false,
        contentType: false,
        processData: false,
        success: (data) => {
           $('#submit').text('submit').removeAttr('disabled');
           this.reset();
           alert('Image has been uploaded using jQuery ajax successfully');
        },
        error: function(data){
           console.log(data);
            $('#submit').text('submit').removeAttr('disabled');
         }
       });
   });
});

</script>

Step 5 – Run and Test Laravel Application

Run php artisan serve command to start the laravel application:

php artisan serve

Finally, open your browser and hit the following URL on it:

http://127.0.0.1:8000/form

Conclusion

We hope that with the help of the example tutorial guide, you have uploaded your images in Laravel 11 application using Ajax without refreshing or reloading the web page.

Happy coding!

Recommended Guides

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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