Laravel 7 Ajax Image Upload Example

10-Apr-2023

.

Admin

Laravel 7 Ajax Image Upload Example

Hi Dev,

This tutorial will provide example of laravel 7 ajax image upload. you will learn laravel 7 image upload using ajax. i explained simply step by step laravel 7 ajax post image upload.

You'll learn jquery ajax image upload laravel 7 example. In this example i can simply use laravel validation and also print laravel error message.

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.

Step 1 : Install Laravel 7 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

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:

following path: .env

DB_HOST=localhost

DB_DATABASE=homestead

DB_USERNAME=homestead

DB_PASSWORD=secret

Step 3: Create images Table and Model

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

php artisan make:model Image -m

After this command you have to put bellow code in your migration file for create Image table.

following path:/database/migrations/2020_01_10_102325_create_images_table.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('image');

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('images');

}

}

Now we require to run migration be bellow command:

php artisan migrate

After you have to put bellow code in your model file for create Image table.

following path:/app/Image.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Image extends Model

{

/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = ['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.open following fille path

following path:/routes/web.php

Route::get('/ajax-image-upload','ImageController@create');

Route::post('/ajax-image-upload','ImageController@store')->name('image.ajax.store');

Step 5: Create Controller

here this step now we should create new controller as ImageUploadAjaxController,So run bellow command for generate new controller

php artisan make:controller ImageController

now this step, this controller will manage layout and image validation with post request,bellow content in controller file.following fille path

following path:/app/Http/Controllers/ImageController.php

<<?php

namespace App\Http\Controller;

use Illuminate\Http\Request;

use Validator;

use App\Image;

class ImageController extends Controller

{

/**

* Show the application ajaxImageUpload.

*

* @return \Illuminate\Http\Response

*/

public function create()

{

return view('create');

}

/**

* Show the application ajaxImageUploadPost.

*

* @return \Illuminate\Http\Response

*/

public function store(Request $request)

{

$input = $request->all();

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

'image' => 'required',

]);

if($validator->passes()){

$imageName = time().'.'.request()->image->getClientOriginalExtension();

$input['image'] = $imageName;

request()->image->move(public_path('photos'), $imageName);

Image::create($input);

return Response()->json(["success"=>"Image Upload Successfully"]);

}

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

}

}

Step 6: Create View

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

following path:resources/views/create.blade.php

<!DOCTYPE html>

<html>

<head>

<title>Laravel 7 Ajax Image Upload</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha256-L/W5Wfqfa0sdBNIKN9cG6QA5F2qx4qICmU2VgLruv9Y=" crossorigin="anonymous" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha256-WqU1JavFxSAMcLP2WIOI+GB2zWmShMI82mTpLDcqFUg=" crossorigin="anonymous"></script>

<meta name="csrf-token" content="{{ csrf_token() }}">

<style type="text/css">

.mt-5{

margin-top: 150px !important;

}

body{

background: #423E3D;

}

</style>

</head>

<body class="bg-dark">

<div class="container">

<div class="row">

<div class="col-md-6 offset-3 mt-5">

<div class="card">

<div class="card-header">

<h5>Laravel 7 Ajax Image Upload - NiceSnippets.com</h5>

</div>

<div class="card-body">

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

<ul></ul>

</div>

<div class="success alert alert-success">

Image Upload Successfully

</div>

<form enctype="multipart/form-data" id="imageUpload">

<div class="form-group">

<label><strong>Image : </strong></label>

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

</div>

<div class="form-group text-center">

<button class="btn btn-success">Save</button>

</div>

</form>

</div>

</div>

</div>

</div>

</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>

<script type="text/javascript">

$(document).ready(function () {

$('.success').hide();// or fade, css display however you'd like.

});

$('#imageUpload').on('submit',(function(e) {

$.ajaxSetup({

headers: {

'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')

}

});

e.preventDefault();

var formData = new FormData(this);

$.ajax({

type:'POST',

url: "{{ route('image.ajax.store')}}",

data:formData,

cache:false,

contentType: false,

processData: false,

complete: function(response)

{

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

$('.success').show();

setTimeout(function(){

$('.success').hide();

}, 5000);

}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>

It will help you...

#Laravel 7