How to image upload using Ajax in Laravel 6

How to image upload using Ajax in Laravel 6

In this post, you will learn how to image upload using Ajax in Laravel 6 App. I write simple tutorial of Laravel 6 Ajax image upload with validation. We will use Jquery form js for Ajax image upload in Laravel 6.

Here I give you full example of Ajax image uploading step by step like create laravel project, migration, model, route, blade file etc. So you have to just follow few steps.

Not issue if you don't know laravel because it is from scratch. After complete this example you will find bellow as like preview, so let's start.

Step 1 : Install Laravel 6 Application

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

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

Step 2 : Database Configuration

In this step, we require to make database configuration, you have to add following details on your .env file.

1.Database Username

1.Database Password

1.Database Name

In .env file also available host and port details, you can configure all details as in your system, So you can put like as bellow:

.env

DB_HOST=localhost

DB_DATABASE=homestead

DB_USERNAME=homestead

DB_PASSWORD=secret

Read Also: Laravel 6 Ajax CRUD Operations Tutorial

Step 3: Create ajax_images Table and Model

In this step we have to create migration for ajax_images table using Laravel 5.3 php artisan command, so first fire bellow command:

php artisan make:migration create_ajax_image_tabel

After this command you will find one file in following path database/migrations and you have to put bellow code in your migration file for create categories table.

<?php


use Illuminate\Support\Facades\Schema;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Database\Migrations\Migration;


class CreateAjaxImageTabel extends Migration

{

    /**

     * Run the migrations.

     *

     * @return void

     */

    public function up()

    {

        Schema::create('ajax_images', function (Blueprint $table) {

            $table->bigIncrements('id');

            $table->string('title');

            $table->string('image');

            $table->timestamps();

        });

    }


    /**

     * Reverse the migrations.

     *

     * @return void

     */

    public function down()

    {

        Schema::drop("ajax_images");

    }

}

Now we require to run migration be bellow command:

php artisan migrate

After create "ajax_images" table you should create AjaxImage model for categories. So first we have to run bellow laravel artisan command for create AjaxImage model:

php artisan make:model AjaxImage

Now, you can see new file on this path app/AjaxImage.php and put bellow content in item.php file:

app/AjaxImage.php

<?php


namespace App;


use Illuminate\Database\Eloquent\Model;


class AjaxImage extends Model

{

    /**

     * The attributes that are mass assignable.

     *

     * @var array

     */

    protected $fillable = [

        'title', 'image'

    ];

}
Step 4: Create Route

In this is step we need to create route for ajax image upload layout file and another one for post request. so open your routes/web.php file and add following route.

routes/web.php

Route::get('ajaxImageUpload', '[email protected]');

Route::post('ajaxImageUpload', '[email protected]')->name('ajaxImageUpload');
Step 5: Create Controller

In this point, now we should create new controller as AjaxImageUploadController in this path app/Http/Controllers/AjaxImageUploadController.php. this controller will manage layout and image validation with post request, So run bellow command for generate new controller:

php artisan make:controller AjaxImageUploadController

Ok, now put bellow content in controller file:

app/Http/Controllers/AjaxImageUploadController.php

<?php


namespace App\Http\Controllers;


use Illuminate\Http\Request;

use Validator;

use App\AjaxImage;


class AjaxImageUploadController extends Controller

{

	/**

     * Show the application ajaxImageUpload.

     *

     * @return \Illuminate\Http\Response

     */

    public function ajaxImageUpload()

    {

    	return view('ajaxImageUpload');

    }


    /**

     * Show the application ajaxImageUploadPost.

     *

     * @return \Illuminate\Http\Response

     */

    public function ajaxImageUploadPost(Request $request)

    {

      $validator = Validator::make($request->all(), [

        'title' => 'required',

        'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',

      ]);


      if ($validator->passes()) {


        $input = $request->all();

        $input['image'] = time().'.'.$request->image->extension();

        $request->image->move(public_path('images'), $input['image']);


        AjaxImage::create($input);


        return response()->json(['success'=>'done']);

      }


      return response()->json(['error'=>$validator->errors()->all()]);

    }

}
Step 6: Create View

In Last step, let's create ajaxImageUpload.blade.php(resources/views/ajaxImageUpload.blade.php) for layout and we will write design code here and also form for ajax image upload, So put following code:

resources/views/ajaxImageUpload.blade.php

<!DOCTYPE html>

<html>

<head>

	<title>Laravel 5 - Ajax Image Uploading Tutorial</title>

	<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

	<script src="http://malsup.github.com/jquery.form.js"></script>

</head>

<body>


<div class="container">

  <h1>Laravel 5 - Ajax Image Uploading Tutorial</h1>


  <form action="{{ route('ajaxImageUpload') }}" enctype="multipart/form-data" method="POST">


  	<div class="alert alert-danger print-error-msg" style="display:none">

        <ul></ul>

    </div>


    <input type="hidden" name="_token" value="{{ csrf_token() }}">


    <div class="form-group">

      <label>Alt Title:</label>

      <input type="text" name="title" class="form-control" placeholder="Add Title">

    </div>


	<div class="form-group">

      <label>Image:</label>

      <input type="file" name="image" class="form-control">

    </div>


    <div class="form-group">

      <button class="btn btn-success upload-image" type="submit">Upload Image</button>

    </div>


  </form>


</div>


<script type="text/javascript">

  $("body").on("click",".upload-image",function(e){

    $(this).parents("form").ajaxForm(options);

  });


  var options = { 

    complete: function(response) 

    {

    	if($.isEmptyObject(response.responseJSON.error)){

    		$("input[name='title']").val('');

    		alert('Image Upload Successfully.');

    	}else{

    		printErrorMsg(response.responseJSON.error);

    	}

    }

  };


  function printErrorMsg (msg) {

	$(".print-error-msg").find("ul").html('');

	$(".print-error-msg").css('display','block');

	$.each( msg, function( key, value ) {

		$(".print-error-msg").find("ul").append('<li>'+value+'</li>');

	});

  }

</script>


</body>

</html>

Make sure you have to create "images" folder in your public directory.

Now we are ready to run our example so run bellow command so quick run:

php artisan serve

Now you can open bellow URL on your browser:

Read Also: Laravel 6 Authentication Tutorial

http://localhost:8000/ajaxImageUpload

I hope it can help you...

Advantages of Hiring PHP Developer for your Website Project

Advantages of Hiring PHP Developer for your Website Project

PHP - Hypertext pre-processor, a scripting language used by many people in developing web pages, but most of us are unaware even of the full form. To train someone and make them learn this whole language is as difficult and time-consuming as it is...

PHP - Hypertext pre-processor, a scripting language used by many people in developing web pages, but most of us are unaware even of the full form. To train someone and make them learn this whole language is as difficult and time-consuming as it is to learn the language yourself. That’s why PHP developers are there to make your life easy. This article will give us the advantages and requirements of Hire PHP Developer for our very own website project.

First of all, let us understand the value the right developer brings to the project and why it is important for your business.

A website is a major component of any company/business and is very important for its face value, the way it represents the company on the internet is critical for any business to succeed. This is the reason why companies are looking for PHP developers who can develop their webpage.

If you're planning to do an online business, your PHP programmer will be the first person to transfer your thinking onto the webpage. You should, therefore, employ developers from PHP to make your hypothetical idea a reality.

With this software programming language, PHP developers all-around can easily build website frameworks, web content management systems, web template systems, and various other web-based designs.

Some of the reasons why we need to outsource these developers are:

Not everyone is the best in each field, all of us have our specific skills and talents hence, PHP developers are also the best at what they do. The time and money spent on the training of the in house employees would be saved if the professional PHP developers are hired. Instead of multitasking, if the employees were to focus on what they’re good at it would increase productivity too.

The PHP developers would be much more professional than the in-house workers. It would lead to the seriousness of work. Hence, on-time delivery is guaranteed with hired PHP developers.

In addition to these benefits, you would also be able to track your project through every stage in constant communication with your online team. These advantages make it incredibly popular and smart to hire a PHP developer.

The PHP developers have in-depth knowledge of PHP, HTML and various frameworks in terms of technical capabilities. Hiring PHP developers are advised to give your website a professional look based on PHP.

Much of web success depends on the involvement of social media. The developer can add to your social networking pages a feature that explicitly redirects visitors. In addition, SEO experts also suggest better connections to the website's social network.

Just like a tailor stitches our dresses according to our preferences and is ready to make last-minute changes. A PHP developer will also be available at the nick of your call to make the website just the way you want it to be and have a customized solution for every problem.

Read also: Why & How to Hire Dedicated PHP Developer

At some point in your business, you’re going to have problems regarding your webpage due to the rapidly changing technology, instead of struggling with ideas like these and not being able to come up with an appropriate solution a PHP web developer could help us with our problems just like any technician would help us with the problems we face in our offices or any architect would help us with designing the structure of a building or any interior designer would help us with setting up our home. The PHP development company are hubs of workers who would help us overcome these problems and are always there.

Source by

Hire PHP Developer and Web Developer for your Online Business

Hire PHP Developer and Web Developer for your Online Business

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application...

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application development. To hire PHP developer and web developer at affordable prices contact Mobiweb Technology via [email protected]

Which is the best PHP Web Development Company in India?

Which is the best PHP Web Development Company in India?

Many experienced players prefer to give it a go ahead with PHP for their web development needs because of the simplicity that PHP provides. PHP is loaded with features that many other languages lack and those pre-defined features can bring new functionalities and finishing touch to your existing or new website that you are looking forward to create. Wouldn’t it be great to get the best PHP Web Development Company for your project; we have a reputation as few of the leading firms in IT industry when it comes to PHP development.

Perks you should keep an eye out for before considering to outsource project to any web development company:

1. Company’s Reputation- It is very important to know about the previous projects that the company has delivered and the success rate of those products. You can visit company’s website for client testimonials or can google reviews given to them by genuine clients. We follow transparency, you can contact our previous clients and let them tell you how their experience was while working with us.

2. Technical Skill set and Expertise- You should select a company that has multiple resource pool of expert and technically sound developers. Our developers are experienced with different PHP frameworks and are exceptionally good with writing bug free codes. You can also hire PHP developer in India from us, as our developers have on hand experience in PHP development (core and frameworks)

3. The Budget- Costing has always played as one of the most important roles in every business deal. We provide competitive pricing with no hidden cost guaranteed. With us you can expect your project to be in best quality with no compromise to be made even with the best price in the market.

Why Data EximIT is the best PHP web development company in India?

Here are some of the features that might love about Data EximIT:

 Reputation of Data EximIT is wonderful among the previous clients.

 We have around 87% of retention ratio of clients.

 We were time committed, means every milestone was achieved before or on time.

 Data EximIT follows Agile development so it was the best possible methodology.

 We have huge team with different expertise over multiple PHP frameworks, so you are provided with ample to options to choose from.

 We are very active in communication part. Method or time of communication was never an issue at Data EximIT.

 We have some of the best designers to ensure that your project not only functions but also looks and feels fabulous.

 We provided customers with best costing without compromising on the quality at all.

 We also provide dedicated PHP developer or team of PHP developers on hire for your project.

Data EximIT is where customers feel confident to come up with idea and leave with fully functioning & best in quality projects. You can also avail our developers at your requested site location if you decide to hire PHP developers in India from us.

Feel free to contact our experts and let success reach you by working with the best PHP web development company.