In this tutorial you will learn about the Laravel 7 Ajax File Upload Ajax Tutorial Example and its application with practical example.
In this Laravel 7 Ajax File Upload Ajax Tutorial Example tutorial I’ll show you how to upload file with ajax in laravel. In this tutorial you will learn to upload file using ajax in laravel. In this step by step tutorial I’ll demonstrate to upload file using ajax in laravel.
Laravel 7 Ajax File Upload Ajax Tutorial Example
- Step 1: Download Laravel New App
- Step 2: Add Database Credentials
- Step 3: Generate Migration & Model
- Step 4: Create Routes For File
- Step 5: Generate Controller by Artisan
- Step 6: Create Blade View For File
- Step 7: Run Development Server
Step 1: Download Laravel New App
First of all we need to create a fresh laravel project, download and install Laravel using the below command
1 |
composer create-project --prefer-dist laravel/laravel Blog |
Step 2: Add Database Credentials
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=here your database name here DB_USERNAME=here database username here DB_PASSWORD=here database password here |
Step 3: Generate Migration & Model
Now, in this step we will create model and migration file. Please run the following command:
1 |
php artisan make:model document -m |
This command will create one model name file and as well as one migration file for the Documents table. Then Navigate to database/migrations folder and open create_documents_table.php. Then update the following code into create_documents_table.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatedocumentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('documents', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('documents'); } } |
Now, run the migration to create database table using following artisan command:
1 |
php artisan migrate |
Step 4: Create Route For File
After this, we need to define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.
routes/web.php
1 2 |
Route::get('file', 'FileController@index'); Route::post('store-file', 'FileController@store'); |
Step 5: Generate Controller by Artisan
Now, lets create a controller named FileController using command given below –
1 |
php artisan make:controller FileController |
Note that, This command will create controller named FileController.php file.
Now app/controllers/ folder and open FileController.php. Then update the following file uploading methods into your FileController.php file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Validator,Redirect,Response,File; use App\Document; class FileController extends Controller { public function index() { return view('file'); } public function store(Request $request) { request()->validate([ 'file' => 'required|mimes:doc,docx,pdf,txt|max:2048', ]); if ($files = $request->file('file')) { //store file into document folder $file = $request->file->store('public/documents'); //store your file into database //$document = new Document(); //$document->title = $file; //$document->save(); return Response()->json([ "success" => true, "file" => $file ]); } return Response()->json([ "success" => false, "file" => '' ]); } } |
Step 6: Create Blade View For File
In this step, create one blade view file named file.blade.php.
So navigate app/resources/views and create one file name file.blade.php. Then update the following code into your file.blade.php file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
<!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 File Upload 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> <style> .container{ padding: 0.5%; } </style> </head> <body> <nav class="navbar navbar-expand-sm bg-primary navbar-dark"> <a class="navbar-brand" href="{{ url('/') }}">w3adda</a> </nav> <div class="container mt-4"> <div class="row"> <div class="col-sm-12"> <h4>File Upload using Ajax in Laravel</h4> </div> </div> <hr /> <form method="POST" enctype="multipart/form-data" id="laravel-ajax-file-upload" action="javascript:void(0)" > <div class="row"> <div class="col-md-12"> <div class="form-group"> <input type="file" name="file" placeholder="Choose File" id="file"> <span class="text-danger">{{ $errors->first('file') }}</span> </div> </div> <div class="col-md-12"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </form> </div> </body> <script type="text/javascript"> $(document).ready(function (e) { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $('#laravel-ajax-file-upload').submit(function(e) { e.preventDefault(); var formData = new FormData(this); $.ajax({ type:'POST', url: "{{ url('store-file')}}", data: formData, cache:false, contentType: false, processData: false, success: (data) => { this.reset(); alert('File has been uploaded successfully'); console.log(data); }, error: function(data){ console.log(data); } }); }); }); </script> </html> |
Step 7: Run Development Server
Now we are ready to run our example so lets start the development server using following artisan command –
1 2 3 |
artisan serve If you want to run the project diffrent port so use this below command php artisan serve --port=8080 |
Now, open the following URL in browser to see the output –
1 2 3 |
http://localhost:8000/file OR hit in browser http://localhost/blog/public/file |