How to upload image with ajax in laravel?

by darrion.kuhn , in category: PHP Frameworks , 6 months ago

How to upload image with ajax in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 6 months ago

@darrion.kuhn 

To upload an image using AJAX in Laravel, you can follow the steps below:

  1. Create a form in your view file to select the image file:
1
2
3
4
5
<form method="POST" enctype="multipart/form-data" id="imageForm">
    @csrf
    <input type="file" name="image" id="image">
    <button type="submit">Upload Image</button>
</form>


  1. Create a script in your view file to handle the AJAX request and submit the form data:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<script>
    $(document).ready(function () {
        $('#imageForm').submit(function (e) {
            e.preventDefault();

            var formData = new FormData($(this)[0]);

            $.ajax({
                url: '/upload',
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                success: function (data) {
                    console.log(data);
                    // do something with the response
                }
            });
        });
    });
</script>


  1. Create a route in your web.php file to handle the AJAX request:
1
Route::post('/upload', 'ImageController@upload');


  1. Create a controller named ImageController with a method upload to handle the file upload:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
namespace AppHttpControllers;

use IlluminateHttpRequest;

class ImageController extends Controller
{
    public function upload(Request $request) {
        $imageName = time().'.'.$request->image->getClientOriginalExtension();
        $request->image->move(public_path('images'), $imageName);

        return response()->json(['success'=>'Image uploaded successfully']);
    }
}


  1. Make sure you have a folder named images in your public directory where the uploaded images will be stored.
  2. That's it! Now you should be able to upload an image using AJAX in Laravel.