How to upload image using ajax in laravel

How to upload image using ajax in laravel

If you are looking for a script through which you can upload image using ajax in laravel than you are on right place:

In this tutorial we will cover following points:

  1. Create route
  2. Create view blade for image upload
  3. Create controller and function for image upload

Step 1: Create Route

In this step we will create route on given path “YourProjectName/routes/web.php”

Copy & Paste below code in “web.php”

Route::group(function(){
	Route::post('uploadimage','HomeController@imageUpload');
});

Step 2: Create View Blade For Image Upload

Create a blade called “welcome.blade.php”. Copy and Paste below code and save it to your “YourProjectName/resources/views” directory.

If you find “welcome.blade.php” file on given path than do not create any other blade and just do copy & paste below code inside that blade for form creation:

<form enctype="multipart/form-data" id="upload_form" role="form" method="POST" action="" >
            @csrf
            <div class="form-group">
                <label for="catagry_name">Logo</label>
                <input type="file" name="logo" class="form-control" id="catagry_logo">
                <p class="invalid">&nbsp;</p>
            </div>
</form>
<div class="modelFootr">
            <button type="button" class="addbtn">Add</button>
</div>

After creating form in blade, now we write a jquery code for ajax:

$(".addbtn").click(function(){
            $.ajax({
                url:'uploadimage', //route name 
                data:new FormData($("#upload_form")[0]), //form data
                dataType:'json',
                async:false,
                type:'post',
                processData: false,
                contentType: false,
                success:function(response){
                    console.log(response);
                },
            });
 });

Step 3: Create Controller & Function For Image Upload

Create a controller called “HomeController.php”. Copy and Paste below code and save it to your “YourProjectName/app/Http/Controllers” directory:

After creating controller, create a function “imageUpload” for image upload.

public function imageUpload(Request $request){
        try{
            $file_name = '';
            if($file = $request->file('logo')){
                $file_name = time().'--'.$file->getClientOriginalName(); //Get the name of file with extension
                $file->storeAs('', $file_name); //Store the file inside storage/app/
            }

            $storagePath = storage_path('app/'.$file_name);
            $mimeType = mime_content_type($storagePath);
            if( ! \File::exists($storagePath)){ //Check file exist on given path or not
                echo 'File Not Found';
            }else{
                echo 'File Uploaded';
            }
        }catch(\Exception $e){
            Log::error('HomeController-imageUpload: '.$e->getMessage());
            return view('error.home');  
        }
}

If you want to save file in your folder than create a folder inside given path: “YourProjectName/storage/app/YourFolderName”

After creating folder just change the following lines inside “imageUpload” function
From:

$file->storeAs('', $file_name);
$storagePath = storage_path('app/'.$file_name);

To:

$file->storeAs('YourFolderName', $file_name);
$storagePath = storage_path('app/YourFolderName'.$file_name);

Find the full code below:

Route:

<?php

Route::group(function(){
	Route::get('/','HomeController@index');
 //function for show the form
 	Route::post('uploadimage','HomeController@imageUpload');
 //function for upload the image
});

Blade:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">

        <!-- Styles -->
        <style>
            html, body {
                background-color: #fff;
                color: #636b6f;
                font-family: 'Nunito', sans-serif;
                font-weight: 200;
                height: 100vh;
                margin: 0;
            }
        </style>
    </head>
    <body>
        <form enctype="multipart/form-data" id="upload_form" role="form" method="POST" action="" >
            @csrf
            <div class="form-group">
                <label for="catagry_name">Logo</label>
                <input type="file" name="logo" class="form-control" id="catagry_logo">
                <p class="invalid">&nbsp;</p>
            </div>
        </form>
        <div class="modelFootr">
            <button type="button" class="addbtn">Add</button>
        </div>
    </body>

    <script src={!! asset('vendors/bower_components/jquery/dist/jquery.min.js')!!}></script>
    <script type="text/javascript">
        $(".addbtn").click(function(){
 //ajax script
            $.ajax({
                url:'uploadimage',
 //route path
                data:new FormData($("#upload_form")[0]),
 //full form data
                dataType:'json',
                async:false,
                type:'post',
                processData: false,
                contentType: false,
                success:function(response){
                    console.log(response);
                },
            });
        });
    </script>
</html>

Controller:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class HomeController extends Controller
{
    //function for show form blade
    public function index(Request $request){
 
        try{
            return view('welcome');
        }catch(\Exception $e){
            Log::error('HomeController-index: '.$e->getMessage());
            return view('error.home');  
        }
    }


    //function for upload image
    public function imageUpload(Request $request){         
        try{
            $file_name = '';
            if($file = $request->file('logo')){
                //get image name with extension
                $file_name = time().'--'.$file->getClientOriginalName();

                //store the image in storage/app directory
                $file->storeAs('', $file_name);
            }

            $storagePath = storage_path('app/'.$file_name);
            $mimeType = mime_content_type($storagePath);

            //check if file exist on given path
            if( ! \File::exists($storagePath)){
                echo 'File Not Found';
            }else{
                echo 'File Uploaded';
            }
        }catch(\Exception $e){
            Log::error('HomeController-imageUpload: '.$e->getMessage());
            return view('error.home');  
        }
    }
}

About Author

Hey, this is Nilesh Sharma and I belong to the Pink City (Jaipur). My job as a software developer has made me a patient man and negotiation my skills! My job also keeps me on my toes, as i always trying to learn new skills to keep pace with the changing technology landscape.

Sign up for weekly update

Milkshake is almost ready. If you're interested in testing it out, then sign up below to get exclusive access.