Laravel 7 Ajax File Upload Ajax Tutorial Example

Laravel 7 Ajax File Upload Ajax Tutorial Example

Laravel 7 ajax file upload example tutorial. Here, you will learn how to upload file using jQuery ajax in laravel app.

As well as how to upload files on MySQL database and web server folder with validation. And also uploading both data and files in one form using ajax in laravel app.

When you work with laravel app. And want to upload files, invoice files, text files using ajax form into the database and server folder in laravel.

So this tutorial will guide you step by step on how to upload file using ajax form submit with validation in laravel.

Note that, this laravel ajax file upload tutorial also works with laravel 5, 5.5, 6, 7.x version.

Laravel Ajax File Upload Example Tutorial

Follow the below following steps and uploading a file using ajax form with validation in laravel app:

  • 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, open your terminal and run the following command to install or download laravel fresh application setup:

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

Step 2: Add Database Credentials

Next, Navigate to your downloaded laravel app root directory and open .env file. Then add your database details in .env file, as follow:

 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

In this step, open a command prompt and run the following command:

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:

<?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');
    }
}

After that, run the following command to migrate the table into your select database:

php artisan migrate

Step 4: Create Route For File

In this step, Navigate to the app/routes folder and open web.php file. Then update the following routes into your web.php file:

 Route::get('file', 'FileController@index');
 Route::post('store-file', 'FileController@store');

Step 5: Generate Controller by Artisan

In this step, open your terminal and run the following command:

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:

<?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:

<!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 - Tutsmake.com</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('/') }}">Tutsmake</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

Finally, run the following command to start the development server:

 php artisan serve

 If you want to run the project diffrent port so use this below command 

 php artisan serve --port=8080  

Now, open your browser and hit the following URLs into it:

 http://localhost:8000/file

 OR hit in browser

 http://localhost/blog/public/file

If you want to remove public or public/index.php from URL In laravel, Click Me

Conclusion

In this file upload using ajax in laravel tutorial, you have learned how to upload file using ajax in laravel app.

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

2 replies to Laravel 7 Ajax File Upload Ajax Tutorial Example

  1. very good. Thanks a lot

  2. Thank you. Verry good.

Leave a Reply

Your email address will not be published. Required fields are marked *