Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kayatech's avatar

how to laravel image upload form vie json api

how to laravel image upload form vie json api

0 likes
3 replies
Tithira's avatar

You can upload images using formData method, then saving your file where you want to store. Do not forget to add enctype="multipart/form-data"to the form. use document.querySelector to select the whole form by its' id #form-submit

blade.php


<form id="form-submit" type="POST"  enctype="multipart/form-data">
	<input type="file" name="file"  >	
	<button type="submit" id="btn-submit">Submit </button>
</form>

<script >
$(document).ready(function () {
	$('#btn-submit').on('click', function(){

		var fd = new FormData(document.querySelector('#form-submit'));    
		// fd.append( 'file', $('#anything_else_you_want_to_add') );					  
			
		$.ajaxSetup({
		        headers: {
		            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
		        }
		});

		$.ajax({
			  url: "{{route('your_post_route_name')}}",
			  data: fd,
			  processData: false,
			  contentType: false,
			  type: 'POST',
			  success: function(data){
			    console.log(data);
			  }
		});
	});	
});
</script>

your route web.php

  Route::post('/home','YourController@store')->name('your_post_route_name');

and your controller logic

public function store(Request $request){

    $this->validate($request, [
        'file' => 'required|image|mimes:jpeg,png,jpg|max:2048',
    ]);


    if ($request->hasFile('file')) {
        $image = $request->file('file');
        $name = $image->getClientOriginalName();                    
        $destinationPath = public_path('/images');
        $image->move($destinationPath, $name);

        $userImage = new UserImage();
        $userImage->name = $name
        $userImage->save();
    }    

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

}
2 likes

Please or to participate in this conversation.