Laravel
984
w3alert.com
11-01-2020
In the previous tutorial, you have learned how to upload single and multiple files or images on the web application folder and MySQL database.
In this ajax image upload in laravel tutorial, we will show you how to upload image using ajax with preview into the database table and folder in laravel. Also, will show a preview of image before uploading on web server and MySQL database.
First Step, you need to download or install laravel web application new setup on your local machine. you can use the following command to download or install laravel application new setup:
composer create-project laravel/laravel laravel-ajax-image-upload –-prefer-dist
If you want to install a specific version of laravel, you can follow the following tutorial
https://w3alert.com/laravel-tutorial/laravel-install-on-windows-ubuntu-with-composer
After that, you will set up the database credentials in .env file. So open your .env file and update database credentials following:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=database_name DB_USERNAME=root DB_PASSWORD=root
Next, we need to create a model and migration in your laravel web application using the php artisan make:model model_name -m. So run the following command in your project root directory.
Go to the command prompt
cd/project_root_directory
php artisan make:model Image -m
after that, go to database/migrations/ and find created migration file and add fields, as you want to in your database table.
Your migration file looks like:
<?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->bigIncrements('id'); $table->string('title'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('Images'); } }
And go to the app/ directory and find the model file.
Your model file looks like:
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Image extends Model { // }
Before you will run php artisan migrate command. Go to app/providers/AppServiceProvider.php and update the below code :
.. use Illuminate\Support\Facades\Schema; .... function boot() { Schema::defaultStringLength(191); } ...
Next, go to command prompt and run the following command:
php artisan migrate OR php artisan migrate:fresh
This php artisan migrate command creates a table in your database.
Next step, go to routes/web.php file and update the following routes into your file:
//display image uploading form Route::get('ajax-image-upload','[email protected]'); //insert files or images into mysql database table laravel Route::post('ajax-image-upload','[email protected]');
Now, you need to generate or create a controller file using artisan command, so use the php artisan make:controller command and generate/create a new controller file:
php artisan make:controller AjaxImageController
In this controller file, we will create 2 methods for display file uploading form and store file into database and folder in laravel web application.
After that, go to App/Http/Controllers/ directory and find the created FileController file and update the following code into your file:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Validator,Redirect,Response; Use App\Image; class AjaxImageController extends Controller { public function index() { return view('ajax-image'); } public function store(Request $request) { request()->validate([ 'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); $response = Response()->json([ "success" => false, "image" => '' ]); if ($files = $request->file('image')) { $destinationPath = 'public/image/'; // upload path $imageName = date('YmdHis') . "." . $files->getClientOriginalExtension(); $files->move($destinationPath, $imageName); $save['title'] = "$imageName"; } $check = Image::insertGetId($save); $response = Response()->json([ "success" => true, "image" => $check ]); return Response()->json($response); } }
Next, you need to create a blade views file, so go resource/views directory and create the following blade views file.
Go to resource/views/ then create a new file name ajax-image.blade.php and update the following code:
<!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 Ajax Image Upload With Preview</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> <nav class="navbar navbar-expand-sm bg-primary navbar-dark"> <a class="navbar-brand" href="{{ url('/') }}">w3alert.com</a> </nav> <div class="container mt-5"> <div class="row"> <div class="col-sm-12"> <h4>Laravel Ajax Image Preview Before Upload</h4> </div> </div> <form method="POST" enctype="multipart/form-data" id="ajax-image-upload-form" action="javascript:void(0)" > <div class="row"> <div class="col-md-12 mb-2"> <img id="display-image-preview" src="" alt="" style="max-height: 150px;"> </div> <div class="col-md-12"> <div class="form-group"> <input type="file" name="image" placeholder="Choose image" id="image"> <span class="text-danger">{{ $errors->first('title') }}</span> </div> </div> <div class="col-md-12"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </form> </div> <script type="text/javascript"> $(document).ready(function (e) { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $('#image').change(function(){ let reader = new FileReader(); reader.onload = (e) => { $('#display-image-preview').attr('src', e.target.result); } reader.readAsDataURL(this.files[0]); }); $('#ajax-image-upload-form').submit(function(e) { e.preventDefault(); var formData = new FormData(this); $.ajax({ type:'POST', url: "{{ url('ajax-image-upload')}}", data: formData, cache:false, contentType: false, processData: false, success: (data) => { this.reset(); alert('Image has been uploaded!'); }, error: function(data){ console.log(data); } }); }); }); </script> </body> </html>
You can use the following command artisan command to start the development server:
php artisan serve
The final step, go to your browser and type the below-given URL into your browser:
http://localhost:8000/ajax-image-upload OR http://localhost/laravel-ajax-image-upload/public/ajax-image-upload
You can also download laravel ajax image upload web application here Download
This tutorial idea has taken from the following urls: