ads

Laravel Ajax Image Upload 


Laravel 6 ajax file upload


hi, I am now explaining about Laravel Ajax Image Upload tutorial. Why am I prefer to create this type of tutorial coz some clients want custom code into your project. Custom code means if they provide you task like I need a page where no-refresh validation or no refresh upload image code then you'll prefer this code for your task

I know there is lot's of article available for this task but I am trying best now to display article like short and sweet and easy to understand for you this Laravel Ajax Image Upload tutorial, my friends.

For validation of laravel of all type validation syntax you can click below


okay let's start tutorial Laravel Ajax Image Upload 

Step: 1 
Create controller, model and migration file using below command

php artisan make:model ajaxImage -mcr

-above command will create 3 files into after once you apply command

I)create a controller file in app/Http/Controller/AjaxImageController.php
II)create model into app/ajaxImage.php
III)create also migration file into database/migration/database/migrations/2020_07_04_112145_create_ajax_images_table.php

Route: 2
Modify migration file like below 

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

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

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

Route: 3 Run migration  

php artisan:migrate

Route: 4 create route into routes/web.php file
Route::get('ajax_image','AjaxImageController@index');
Route::post('ajax_image','AjaxImageController@store');

Route: 5 Modify controller & model file like below code

app/AjaxImage.php


<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class ajaxImage extends Model
{
    protected $guarded = [];
}

In Laravel, fillable attributes are used to specify those fields which are to be mass assigned. Guarded attributes are used to specify those fields which are not mass assignable.

app/Http/Controller/AjaxImageController.php

<?php
namespace App\Http\Controllers;

use App\ajaxImage;
use Illuminate\Http\Request;
use Validator;

class AjaxImageController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('ajaxImage');
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
      try {
        $validator = Validator::make($request->all(), [
          'ajax_images' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);
        if ($validator->passes()) {
          $input = $request->all();
          $input['ajax_images'] = time().'.'.$request->ajax_images->getClientOriginalExtension();
          $request->ajax_images->move(public_path('ajax_images'), $input['ajax_images']);
          AjaxImage::create($input);
          return response()->json(['status' => true,'msg'=> 'Successfully file uploaded by ajax code']);
        }else{
           return response()->json(['status' => false,'msg'=>$validator->errors()->all()]);
        }
      } catch (\Exception $e) {
        return response()->json(['status' => false,'msg'=> $e->getMessage()]);
      }
    }
}

In the above controller, you can show I am using try{}catch(){} and also using validator coz of catch the error if any function error it will catch into catch function and it there is any error into validation than it will pass into else condition of validation

Route: 6 create blade file which is defined into ajax_image get method route of index function

resources/views/ajaxImage.blade.php


<!DOCTYPE html>
<html>
<head>
    <title>Laravel Import Export CSV - <a href="https://www.mtitsolutions.in/">MTitsolutions</a></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>

<div class="container">
    <div class="card">
        <div class="card-header">
            Laravel Import Export CSV - <a href="https://www.mtitsolutions.in/">MTitsolutions</a>
        </div>
        <div class="card-body">
            <div class="alert alert-success" style="display: none;">
              <strong>Success!</strong> <p></p>
            </div>
            <div class="alert alert-danger" style="display: none;">
              <strong>Error!</strong> <p></p>
            </div>
            <form action="{{ route('ajax_image') }}" method="POST" class="ajax_image_upload" enctype="multipart/form-data">
                @csrf
                <input type="file" name="ajax_images" class="form-control" required>
                <br>
                <button class="btn btn-primary">Upload File</button>
            </form>
        </div>
    </div>
</div>

<script type="text/jscript">
  $(document).ready(function(){
    $(document).on("submit", "form.ajax_image_upload" , function(e){
            e.preventDefault();
            var formData = new FormData(this);
            var url = $(this).attr('action');
            $.ajax({
                type: 'POST',
                url:url,
                data:formData,
                success: function (data) {
                  if(data.status == 1){
                    $('.alert-success p').text(data.msg);
                    $('.alert-success').show();
                    $('.alert-danger').hide();
                  }
                  else{
                    $('.alert-danger p').text(data.msg);
                    $('.alert-danger').show();
                    $('.alert-success').hide();
                  }
                },
                cache: false,
                contentType: false,
                processData: false
            });
        return false;
    });
  });
</script>
</body>
</html>

Output:

http://127.0.0.1:8000/ajax_image



View On Github

That's it.
Happy coding.
I hope this post will help you a lot.


Post a Comment

Previous Post Next Post