Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 Ajax File Upload Tutorial

Last Updated on April 18, 2024 by

In Laravel 11, Ajax File Upload allows users to upload files in the background instead of submitting a form and reloading the entire page.

Let’s start implementing file upload feature in project using jQuery AJAX:

Step 1: Create Blade View and Form

Create upload.blade.php view in resources/views for rendering the upload form and displaying success or error messages. And then create file upload form in it, like the following:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 11 AJAX File Upload Tutorial - ITCODSTUFF.COM</title>
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        /* Custom CSS for file upload form */
        .card {
            border-radius: 15px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .card-header {
            background-color: #007bff;
            color: white;
            border-bottom: none;
            border-radius: 15px 15px 0 0;
        }
        .btn-primary {
            background-color: #007bff;
            border-color: #007bff;
        }
        .btn-primary:hover {
            background-color: #0056b3;
            border-color: #0056b3;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">Laravel AJAX File Upload - ITCODSTUFF.COM</div>
                    <div class="card-body">
                        <form id="uploadForm" action="{{ route('upload') }}" method="POST" enctype="multipart/form-data">
                            @csrf
                            <div class="mb-3">
                                <input type="file" class="form-control" name="file" id="file">
                            </div>
                            <button type="submit" class="btn btn-primary">Upload File</button>
                        </form>
                        <div id="message" class="mt-3"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>


</body>
</html>

Step 2: Implement AJAX Functionality

Use jquery to handle form submission with file data via AJAX requests for file uploads. Use FormData to send files asynchronously to the server.

    <!-- jQuery -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $('#uploadForm').submit(function(e){
                e.preventDefault();

                var formData = new FormData(this);

                $.ajax({
                    url: $(this).attr('action'),
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response){
                        $('#message').html('<div class="alert alert-success">File uploaded successfully: ' + response.filename + '</div>');
                    },
                    error: function(xhr, status, error){
                        $('#message').html('<div class="alert alert-danger">Error: ' + xhr.responseText + '</div>');
                    }
                });
            });
        });
    </script>

Step 3: Create File Upload Controller

Use artisan command to generate a controller file:

php artisan make:controller FileUploadController

Step 4: Define Method to Handle AJAX Requests

Edit app/http/controllers/FileUploadController.php file and define methods into it for rendering the upload form and handling the file upload via ajax:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FileUploadController extends Controller
{
    public function index()
    {
        return view('upload');
    }

    public function upload(Request $request)
    {
        if ($request->hasFile('file')) {
            $file = $request->file('file');

            // Validate the uploaded file
            $validated = $request->validate([
                'file' => 'required|file|max:2048', // Max file size of 2MB
            ]);

            // Generate a unique file name
            $filename = time().'_'.$file->getClientOriginalName();

            // Move the uploaded file to the storage directory
            $file->move(public_path('uploads'), $filename);

            // Return a success response
            return response()->json(['success' => true, 'filename' => $filename]);
        }

        // Return an error response if no file is uploaded
        return response()->json(['error' => 'No file uploaded.'], 400);
    }
}

Step 5: Define Routes

Define routes in routes/web.php for handling file upload requests via ajax:

use App\Http\Controllers\FileUploadController;

Route::get('/form', [FileUploadController::class, 'index']);
Route::post('/upload', [FileUploadController::class, 'upload'])->name('upload');

Step 6: Test Application

Start application server using artisan command:

php artisan serve

Hit http://127.0.0.1:8000/form url on browser for testing:

In the tutorial steps, you create a form in your Laravel application with a file input field and use the jquery file input change event or button click event, and use AJAX to send the data to the server asynchronously , and create a controller and route with methods to handle AJAX requests for file uploading.

Leave a Comment