DEV Community

Cover image for Laravel 8 Ajax Image Upload Example
Code And Deploy
Code And Deploy

Posted on

2 1

Laravel 8 Ajax Image Upload Example

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/laravel/laravel-8-ajax-image-upload-example

In this post, I will share an example of how to upload an image in Laravel 8 using ajax. In my previous post, I posted about Laravel image upload without ajax. Now let's do the ajax function so that our page will not need to reload after submitting the request to our server.

ajax-laravel-8-image

ajax-laravel-8

To make it short just use my previous tutorial about Laravel image upload then integrate the ajax.

Okay, let's start I assume that you already followed my previous tutorial.

Step 1: Update our Controller Code for Laravel Ajax Image Upload

Below code is our updated code to support the Laravel ajax image upload.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\ImageUploadRequest;

class ImageUploadController extends Controller
{
    public function index() 
    {
        return view('image-upload.index');
    }

    public function upload(ImageUploadRequest $request) 
    {

        $filename = time() . '.' . $request->image->extension();

        $request->image->move(public_path('images'), $filename);

        // save uploaded image filename here to your database

        return response()->json([
            'message' => 'Image uploaded successfully.',
           'image' => 'images/' . $filename
        ], 200);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Update for View

Now let's update our view code to support the ajax functionality. See below code:

<!DOCTYPE html>
    <html>

    <head>
        <meta charset="utf-8" />
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Laravel 8 Image Upload Example - codeanddeploy.com</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>

        <style type="text/css">
            .error {
                color: red
            }

            #image {
                display: none;
            }
        </style>

        <script type="text/javascript">
            $(document).ready(function(){
              $('#laravel-image-upload').on('submit', function(event){
                    event.preventDefault();

                    var url = $('#laravel-image-upload').attr('data-action');

                    $.ajax({
                        url: url,
                        method: 'POST',
                        data: new FormData(this),
                        dataType: 'JSON',
                        contentType: false,
                        cache: false,
                        processData: false,
                        success:function(response)
                        {
                            $('#image').attr('src', response.image).show();

                            alert(response.message)
                        },
                        error: function(response) {
                            $('.error').remove();
                            $.each(response.responseJSON.errors, function(k, v) {
                                $('[name=\"image\"]').after('<p class="error">'+v[0]+'</p>');
                            });
                        }
                    });
                });

            });
        </script>
    </head>

    <body>
        <div class="container mt-5">
            <img width="200px" id="image">

            <form data-action="{{ route('image-upload.post') }}" method="POST" enctype="multipart/form-data" id="laravel-image-upload">
                @csrf
                <div class="row">

                    <div class="col-md-6">
                        <input type="file" name="image" class="form-control">
                    </div>

                    <div class="col-md-6">
                        <button type="submit" class="btn btn-success">Upload</button>
                    </div>

                </div>
            </form>
        </div>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Now you have an idea already how to do the Laravel 8 image upload using ajax. I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/laravel-8-ajax-image-upload-example if you want to download this code.

Happy coding :)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay