Laravel 11 Ajax File Upload Example

Laravel 11 Ajax File Upload Example

Ajax file upload in laravel 11; Create a file upload form and write jQuery AJAX code into it to submit form data on the controller to upload file to the public storage folder in Laravel application without refreshing the page.

In this guide, we will show you how to upload a file without refreshing the page using jQuery Ajax with form in Laravel 11 application.

How to Upload File using Ajax in Laravel 11?

Here are steps to upload a file using jQuery ajax without refreshing the page in laravel 11:

Step 1 – Create New Laravel Application

Run the composer create-project --prefer-dist laravel/laravel blog command on cmd or terminal window to create a new laravel application in to your system:

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

Step 2 – Define Ajax File Upload Routes

Now create routes on web.php to upload files using Ajax, which you can create like this:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\MediaController;

Route::get('/ajax-file-upload', [MediaController::class, 'index']);
Route::post('/ajax-file-upload', [MediaController::class, 'uploadFile']);

Step 3 – Create Controller to Handle Ajax File

Run php artisan make:controller MediaController to create a controller file, which is used to handle ajax file upload:

php artisan make:controller MediaController

Now, open the MediaController.php file from the app/http/controllers folder, and write two methods in it to handle AJAX file upload methods; as given below:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class MediaController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('ajax-file-upload');
    }
      
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function uploadFile(Request $request)
    {
        //validate file type and size
        $request->validate([
            'file' => 'required|mimes:doc,docx,pdf,zip,rar|max:2048',
        ]);
                 
         //upload file in folder 
        $path = $request->file('file')->store('public/files');

        //write code to save file in database
        
        return response()->json('File uploaded successfully');
    }
}

Step 4 – Create Ajax File Upload Form in View

Create a view file named ajax-file-upload.blade.php and create a form in it with the help of which the user can select the file to upload; Like the following:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Ajax File Upload Example - Tusmake.com</title>
    
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
       
<div class="container">
         
    <div class="panel panel-primary card mt-5">
    
        <div class="panel-heading text-center mt-4">
            <h2>Laravel 11 Ajax File Upload Example - Tusmake.com</h2>
        </div>
   
        <div class="panel-body card-body">
           
            <form action="{{ url('ajax-file-upload') }}" method="POST" id="file-upload" enctype="multipart/form-data">
                @csrf
        
                <div class="mb-3">
                    <label class="form-label" for="inputFile">Select File:</label>
                    <input 
                        type="file" 
                        name="file" 
                        id="inputFile"
                        class="form-control">
                    <span class="text-danger" id="file-input-error"></span>
                </div>
         
                <div class="mb-3">
                    <button type="submit" class="btn btn-success">Upload</button>
                </div>
            
            </form>
        
        </div>
    </div>

</div>

</body>
      
</html>

Step 5: Write jQuery Ajax Code to Send Form Data to Server

Now use the ajax() method of jQuery AJAX to send the form data to the server or controller to process it and store the file on the folder and database, like the following:

<script type="text/javascript">

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
  
    $('#file-upload').submit(function(e) {
        e.preventDefault();
        let formData = new FormData(this);
        $('#file-input-error').text('');

        $.ajax({
            type:'POST',
            url: "{{ url('ajax-file-upload') }}",
            data: formData,
            contentType: false,
            processData: false,
            success: (response) => {
                if (response) {
                    this.reset();
                    alert('File has been uploaded successfully');
                }
            },
            error: function(response){
                $('#file-input-error').text(response.responseJSON.message);
            }
       });
    });
      
</script>

Step 6 – Run and Test Application

Run the php artisan serve command to start the application for testing:

php artisan serve

Use http://localhost:8000/ajax-file-upload URL on your browser:

http://localhost:8000/ajax-file-upload

Conclusion

We hope that with the help of this simple guide you have been able to upload files from a form using jQuery Ajax, that too without refreshing the page in laravel 11 applications.

If you still have any questions about this guide, you can ask us by commenting in the comment box given below.

Recommended Guides

AuthorAdmin

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 *