Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
Laravel 11 Ajax Image Upload with form with example

Laravel 11 Ajax Image Upload with form with example

Aman Jain, July 16, 2024July 16, 2024

In this tutorial, I will demonstrate how to implement Laravel 11 Ajax Image Upload with form. This can be achieved using Laravel’s file and storage providers. In our previous articles, such as How to Upload image in Laravel 11 ? we explained how to upload images without Ajax. However, today I’ll show you how to upload images using jQuery Ajax. Image uploading on a website serves various purposes, such as setting a profile picture or submitting documents. Laravel offers powerful features for securely uploading and processing images

Laravel 11 Ajax Image Upload Steps

In Laravel, you can easily access uploaded files using the Request class’s file method, allowing you to store or validate them using Laravel’s built-in methods. Laravel also supports uploading images to various cloud servers like AWS.

There are numerous features and packages available for Laravel online. This tutorial focuses on demonstrating how Laravel handles image uploading using its built-in methods.

We’ll utilize the jQuery JavaScript library in this tutorial to send Ajax requests to the server and perform image uploads as follows:

<script>
 $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
});
$("form").submit(function(e) {
    e.preventDefault();    
    var formData = new FormData(this);

    $.ajax({
        url: "url-to-upload",
        type: 'POST',
        data: formData,
        success: function (data) {
            //handle response        },
        cache: false,
        contentType: false,
        processData: false
    });
});
</script>

Also Read : How to use Post Ajax Request in Laravel 8 / 9?

In this tutorial, we will create two routes, a controller, a model, a view, and a JavaScript file to enable image file preview using Ajax in Laravel. Let’s begin with a simple, step-by-step example of Ajax Image Upload with Preview in Laravel

Step 1: Create a fresh laravel project

Open a terminal window and type below command to create a new project

composer create-project --prefer-dist laravel/laravel blog

You can also read this to start with new project

Step 2 : Create a table and model

For example, I’ll begin by creating a table using migration and then populate it with data. First, let’s generate the model and migration files

php artisan make:model Article -m

this will generate the model and migration file

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    use HasFactory;
    
}

and migration file database/migrations/timestamp_create_articles_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;


return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
     public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->string('email')->unique();;
            $table->string('title');
            $table->string('body')->nullable();
            $table->string('image');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('articles');
    }
}

and then migrate the migration

php artisan migrate

Step 3 : Create controller

Let’s create a controller and add a methods showArticle and addArticle

php artisan make:controller ArticleController

and add the below code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Article;
use Illuminate\Support\Facades\Validator;

class ArticleController extends Controller
{
   public function showForm(Request $request)
  {
    return view('articles.form');
  }

  function uploadArticle(Request $request)
  {

    $validator = Validator::make($request->all(), [
      'title' => "required",
      'email' => "required|email",
      'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
    ]);
    if ($validator->fails()) {
      return response()->json($validator->errors(), 422);
    }
    $file = $request->file("image")->store("uploads/images");

    //  save image and name in database
    $Article = new Article();
    $Article->title = $request->title;
    $Article->email = $request->email;
    $Article->image = $file;
    $Article->save();
    return response()->json(["status" => true, "message" => "Image uploaded successfully"]);
  }
}

In above code we used this code to store the image

 $file = $request->file("image")->store("uploads/images");
         
         //  save image and name in database
           $Article=new Article();
           $Article->title=$request->title;
           $Article->email=$request->email;
           $Article->image= $file;
           $Article->save();

Step 4: Create blade file for view

Now it’s time to show the form and validation message to our view, so let’s create the view file.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Laravel 11 Ajax Image Upload with form with example - Readerstacks </title>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
  <link href="//netdna.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />

</head>

<body>
  <div class="container">

    <div class="panel panel-primary">
      <div class="panel-heading">
        <h2>Laravel 11 Ajax Image Upload with form with example - Readerstacks</h2>
      </div>
      <div class="panel-body">

        <form method="post" id="uploadimageform" action="{{url('upload-article')}}" name="registerform">
          <div class="form-group">
            <label>Email</label>
            <input type="text" name="email" value="" class="form-control" />
            @csrf
          </div>
          <div class="form-group">
            <label>Phone number</label>
            <input type="text" name="phone_number" value="" class="form-control" />

          </div>
          <div class="form-group">
            <label>Title</label>
            <input type="text" name="title" value="" class="form-control" />

          </div>

          <div class="form-group">
            <label>Image</label>
            <input type="file" placeholder="Image" name="image" id="imgInp">
            <img style="visibility:hidden" id="prview" src="" width=100 height=100 />

          </div>

          <div class="form-group">
            <button class="btn btn-primary">Upload</button>
          </div>
        </form>


      </div>
    </div>
  </div>
</body>
<script>
  $(function() {
    $("#uploadimageform").on("submit", function(e) {
      e.preventDefault();
      var action = $(this).attr("action");
      var method = $(this).attr("method");
      if (method == "post") {
      
        var formData = new FormData(this);

        $.ajax({
          url: action,
          type: 'POST',
          data: formData,
          success: function(data) {
            alert("Form submitted successfully")
          },
          error: function(response, textStatus, errorThrown) {
            console.log(response, textStatus, errorThrown)
            $(".alert").remove();
            var erroJson = JSON.parse(response.responseText);
            for (var err in erroJson) {
              for (var errstr of erroJson[err])
                $("[name='" + err + "']").after("<div class='alert alert-danger'>" + errstr + "</div>");
            }
          },
          cache: false,
          contentType: false,
          processData: false
        });

      }
      return false;

    });
  });
</script>

</html>

Step 5: Add jQuery to handle the form submit

Here is the main logic to handle the form submit using jquery. In this step we will handle form submit using the query post method.

<script>
  $(function() {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        } 
    });
    $("#uploadimageform").on("submit", function(e) {
      e.preventDefault();
      var action = $(this).attr("action");
      var method = $(this).attr("method");
      if (method == "post") {
      
        var formData = new FormData(this);

        $.ajax({
          url: action,
          type: 'POST',
          data: formData,
          success: function(data) {
            alert("Form submitted successfully")
          },
          error: function(response, textStatus, errorThrown) {
            console.log(response, textStatus, errorThrown)
            $(".alert").remove();
            var erroJson = JSON.parse(response.responseText);
            for (var err in erroJson) {
              for (var errstr of erroJson[err])
                $("[name='" + err + "']").after("<div class='alert alert-danger'>" + errstr + "</div>");
            }
          },
          cache: false,
          contentType: false,
          processData: false
        });

      }
      return false;

    });
  });
</script>

Here, we added ("#uploadimageform").on("submit", function() {} to handle the submit event of form. Then, create a post request using $.ajax and also get the value of form action.

In next line we are handling the fail and success state. if the AJAX failed then it come into the fail block (Http response code 422). if the response code is 200 then it will come into success block.

              $(".alert").remove();
              var erroJson = JSON.parse(response.responseText);
              for (var err in erroJson) {
                for (var errstr of erroJson[err])
                  $("[name='" + err + "']").after("<div class='alert alert-danger'>" + errstr + "</div>");
              }

Above code we are using to show the validation message below the each field.

Step 6 : Create Symblink for Storage

This is an important step and i suggest you to not skip this step, if you are going to show images in your website because you must need to access the image to show it on website so open config\filesystems.php and add public_path('uploads') => storage_path('app/uploads') to links block

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default filesystem disk that should be used
    | by the framework. The "local" disk, as well as a variety of cloud
    | based disks are available to your application. Just store away!
    |
    */

    'default' => env('FILESYSTEM_DRIVER', 'public'),
    'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
            'endpoint' => env('AWS_ENDPOINT'),
            'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
        ],

    ],
    'links' => [
        public_path('storage') => storage_path('app/public'),
        public_path('uploads') => storage_path('app/uploads'),
    ],

];

Since we are using in our controller this code

$destinationPath= '/uploads/images';
         
$storageDestinationPath=storage_path('app'.$destinationPath);

so we created a Symblink as

 public_path('uploads') => storage_path('app/uploads'),

Now run artisan command to run Symblink

php artisan storage:link

Or for shared hosting

Route::get('/artisan-link', function () {
    Artisan::call('storage:link');
});

NOTE: If you are using php artisan serve and virtual host to serve your application then above method will work perfectly but in case you are putting your public/index.php in root folder then you need to add public in URL. Example

URL for php artisan serve and virtual host will be and this will work perfectly

http://localhost:8000/uploads/images/16525039733751202249.png 

and you are putting your public/index.php in root folder then you need to add public in URL

http://localhost/projectname/public/uploads/images/16525039733751202249.png 

Step 7 : Create two routes in routes/web.php

One route for preview the html and another route for upload and compress the image.

routes/web.php

<?php

use App\Http\Controllers\ArticleController;
use Illuminate\Support\Facades\Route;


Route::get('/form',"ArticleController@showForm");
Route::post('/upload-article',"ArticleController@uploadArticle");

In conclusion, this tutorial has covered the essential steps to implement Ajax image upload with preview in Laravel. We started by setting up routes, creating a controller, and establishing a model for handling image uploads. Additionally, we created a view with JavaScript to enable image preview functionality on the client side.

By following these steps, you should now have a solid understanding of how to integrate Ajax-based image uploading into your Laravel application, enhancing user experience and interaction with seamless file handling. Remember to adapt and extend these concepts as per your specific application requirements and further explore Laravel’s robust features for more advanced functionalities. Happy coding!

Related

Php Laravel Laravel 11 ajaximageuploadlaravel

Post navigation

Previous post
Next post

Related Posts

Php How to use laravel whereNotIn query with example

How to use laravel whereNotIn query with example ?

October 15, 2022March 16, 2024

In this guide we will learn to create SQL not in query using laravel whereIn eloquent builder. whereNotIn laravel can used multiple ways to build the query one the of the feature of laravel eloquent is creating dynamic query based on condition and sub queries too. To create where not…

Read More
Php How to create multiple size thumbs from image in laravel

How to create multiple size thumbs from image in laravel 8 ?

May 14, 2022February 22, 2024

Resizing images can be a best performance booster for any application since this will load the proper size images. In this article i will show you to create multiple size thumbs from image in laravel using intervention package. Big size of image can reduce the performance of the application therefor…

Read More
Php How to Get Only Soft Deleted Records in Laravel 9

How to Get Only Soft Deleted Records in Laravel 9 ?

June 20, 2022June 20, 2022

In this article we will learn to get only soft deleted records in Laravel. In our recent article Use Soft Delete to Temporary (Trash) Delete the Records in Laravel 9 we learnt to delete the file without actually deleting from database and sometimes we want to show only that records…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version