Laravel 10 Ajax File Upload Tutorial

Laravel 10 Ajax File Upload Tutorial

Sometimes, you need to upload file without page refresh in your laravel web application.

So, In this tutorial, you will learn how to upload file using jQuery Ajax in laravel 10 apps without reloading or refreshing the whole web page.

File Upload using Ajax in Laravel 10

You can follow these steps to upload a file (txt, pdf, gif, png, etc) using AJAX in Laravel 10:

  • Step 1 – Setup New Laravel 10 Application
  • Step 2 – Setup Database with App
  • Step 3 – Create Model & Migration
  • Step 4 – Define Routes
  • Step 5 – Create Controller By Artisan Command
  • Step 6 – Create Blade View
  • Step 7 – Run Development Server

Step 1 – Setup New Laravel 10 Application

First of all, start your terminal to download or install Laravel 10 new setup. Run the following commands in it to install the new Laravel 10 app on your system:

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

Step 2 – Setup Database with App

In this step, Configure your database with your apps. So, visit your app root directory and find .env file. Then configure database details as follows:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database-name
DB_USERNAME=database-user-name
DB_PASSWORD=database-password

Step 3 – Create Model & Migration

In this step, open again your command prompt. And run the following command on it. To create model and migration file for the form:

php artisan make:model Photo -m

After that, open create_photos_table.php file inside blog/database/migrations/ directory. And the update the function up() with following code:

    public function up()
    {
        Schema::create('photos', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('path');
            $table->timestamps();
        });
    }

Then, open again command prompt and run the following command to create tables into database:

php artisan migrate

Then visit app/Models/directory and open Photo.php file and add the following code into it:

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Photo extends Model
{
    use HasFactory;

    protected $table = 'photos';
  
    protected $fillable = [
        'name'
    ];
}

Step 4 – Define Routes

In this step, Visit your routes directory and open web.php file in any text editor. And add the following routes into web.php route file:

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\FileUploadController;
  
/* 
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::controller(FileUploadController::class)->group(function(){
    Route::get('file-upload', 'index');
    Route::post('file-upload', 'store')->name('file.store');
});

Step 5 – Create Controller By Artisan Command

In this step, execute the following command on terminal/command prompt/command line to create controller file for your laravel applications; is as follow:

php artisan make:controller FileUploadController

After that, go to app/http/controllers and open FileUploadController.php file. And update the following code into it:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Photo;
  
class FileUploadController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('fileUpload');
    }
      
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:doc,docx,pdf,zip,rar|max:2048',
        ]);
        
        $fileName = time().'.'.$request->file->extension();  
         
        $request->file->move(public_path('file'), $fileName);
      
        Photo::create(['name' => $fileName]);
        
        return response()->json('File uploaded successfully');
    }
}

Step 6 – Create Blade View

Now, create a file upload form in the blade view file to display the file upload form and submit it to the database.

So, Go to resources/views and create fileUpload.blade.php and update the following code into it:

<!DOCTYPE html>
<html>
<head>
    <title>How to Upload File using Ajax in Laravel 10? - Tusmake.com</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
       
<div class="container">
         
    <div class="panel panel-primary card mt-5">
    
        <div class="panel-heading text-center mt-4">
            <h2>How to Upload File using jquery Ajax in Laravel 10? - Tutsmake.com</h2>
        </div>
   
        <div class="panel-body card-body">
           
            <form action="{{ route('file.store') }}" method="POST" id="file-upload" enctype="multipart/form-data">
                @csrf
        
                <div class="mb-3">
                    <label class="form-label" for="inputFile">Select File:</label>
                    <input 
                        type="file" 
                        name="file" 
                        id="inputFile"
                        class="form-control">
                    <span class="text-danger" id="file-input-error"></span>
                </div>
         
                <div class="mb-3">
                    <button type="submit" class="btn btn-success">Upload</button>
                </div>
            
            </form>
        
        </div>
    </div>

</div>

</body>
  
<script type="text/javascript">

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
  
    $('#file-upload').submit(function(e) {
        e.preventDefault();
        let formData = new FormData(this);
        $('#file-input-error').text('');

        $.ajax({
            type:'POST',
            url: "{{ route('file.store') }}",
            data: formData,
            contentType: false,
            processData: false,
            success: (response) => {
                if (response) {
                    this.reset();
                    alert('File has been uploaded successfully');
                }
            },
            error: function(response){
                $('#file-input-error').text(response.responseJSON.message);
            }
       });
    });
      
</script>
      
</html>

Step 7 – Run Development Server

Finally, open the command prompt or cmd and run the following command to start development server:

php artisan serve

Then open your browser and hit the following url on it:

http://localhost:8000/file-upload

Conclusion

That’s all; In this tutorial, you have learned how to upload file using jQuery ajax in laravel 10 application.

Recommended Laravel Posts

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including 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. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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