Upload Image in Laravel 8 using Ajax

Upload Image in Laravel 8 using Ajax

Upload Image in Laravel 8 using Ajax Example Tutorial

In this article, we explain how to upload images in Laravel 8 using ajax jquery Example Tutorial from scratch step by step. More than the time we need to save the image data with an ajax request in the Laravel app without page reload and refresh. If you know then uploading an image in Laravel using ajax and save in a database is too easy. Here we upload files using ajax in Laravel with validations save in the database and remove image and preview option as well. Laravel makes it very easy to store uploaded files using the store method on an uploaded file instance. Call the store method with the path at which you wish to store the uploaded file. So guys let’s checkout Upload Image in Laravel 8 using Ajax with showing validation, preview image and remove image option here.

Step 1: Install Laravel 8 App

First, install Laravel 8 application just run the below command.

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

Step 2: Setup Database

Now set up your database, open your .env file, and add the database name, username, and password to it.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_images
DB_USERNAME=root
DB_PASSWORD=

Step 3: Create Model & Migrations

Now generate the model and migration file just running the below command.

php artisan make:model Image -m

The command generates two files one is a model and another is a migration file, You need to add a fillable property in the model and open the migration file and add the below code.

database\migrations\2020_09_13_082159_create_images_table.php

<?php

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

class CreateImagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('name')->nullable();
            $table->string('path')->nullable();
            $table->timestamps();
        });
    }

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

After adding the code in your migration file now run the migrate command which generates a new table in your database.

php artisan migrate

Add Fillable Property in Model

If we store data in the database then we need to update a fillable property in the model means which columns we must update when we store the data.

app\Image.php

    /**
      * The attributes that are mass assignable.
      *
      * @var array
      */
     protected $fillable = [
         'name', 'path'
     ];

Step 4: Make Routes

Now in this step, you need to add two routes in your web.php file same as below.

routes\web.php

<?php

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


Route::get('upload-images','App\Http\Controllers\ImageController@index');
Route::post('upload-images','App\Http\Controllers\ImageController@storeImage')->name('images.store');
Route::get('/', function () {
    return view('welcome');
});

Step 5: Create Controller

Create a new controller.

php artisan make:controller ImageController

After running the above command you got a new controller file open and put the below code on it.

app/Http/Controllers/ImageController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Image;

class ImageController extends Controller
{
    public function index()
    {

      return view('images');
    }

    public function storeImage(Request $request)
    {
        $request->validate([
          'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        $image = new Image;

        if ($request->file('file')) {
            $imagePath = $request->file('file');
            $imageName = $imagePath->getClientOriginalName();

            $path = $request->file('file')->storeAs('uploads', $imageName, 'public');
        }

        $image->name = $imageName;
        $image->path = '/storage/'.$path;
        $image->save();

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

Step 6: Create Blade File

Now create an image file in the view section and put the below code on it.

resources\views\images.blade.php

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>Laravel Image Upload Using Ajax Example</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>

<div class="container mt-4">
  <h2>Laravel Image Upload Using Ajax Example</h2>
    <form method="post" id="upload-image-form" enctype="multipart/form-data">
        @csrf
        <div class="form-group">
            <input type="file" name="file" class="form-control" id="image-input">
            <span class="text-danger" id="image-input-error"></span>
        </div>

        <div class="form-group">
          <button type="submit" class="btn btn-success">Upload</button>
        </div>

    </form>
</div>

<script>
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

   $('#upload-image-form').submit(function(e) {
       e.preventDefault();
       let formData = new FormData(this);
       $('#image-input-error').text('');

       $.ajax({
          type:'POST',
          url: `/upload-images`,
           data: formData,
           contentType: false,
           processData: false,
           success: (response) => {
             if (response) {
               this.reset();
               alert('Image has been uploaded successfully');
             }
           },
           error: function(response){
              console.log(response);
                $('#image-input-error').text(response.responseJSON.errors.file);
           }
       });

  });

</script>
</body>
</html>

NOTE: Run the Laravel storage link command for uploading images in public and storage directory.

php artisan storage:link

Step 7: Create the “uploads” Directory

Create an uploads folder in your public directory. In ubuntu we need to add permission for our folder, you can take the below command to give permission to your directory, and then you can upload images easily in your database.

Permission to the public folder:

sudo chmod -R 777 public/uploads

Permission to the public folder:

sudo chmod -R 777 storage

So guys, today we learn Laravel 8 Ajax Image Upload with Validations Tutorial Example. I hope its work for you, if any question please comment below.

Reactions

Post a Comment

0 Comments

close