Laravel 9 File Upload using Ajax Example Tutorial
Hi Dev,
Here, I will show you Laravel 9 File Upload using Ajax Example Tutorial. if you have question about Laravel 9 File Upload using Ajax Example then I will give simple example with solution. you'll learn How to Upload File using Ajax in Laravel 9?. This article goes in detailed on how to upload file in laravel 9 using ajax jquery Example. You just need to some step to done how to upload file using ajax request.
This article will give you simple example of Laravel 9 – Ajax file upload example tutorial step by step
Let's start following example:
Step 1: Install LaravelFirst of all we are going from scratch new laravel application. if you have already created the project, then skip following step.
composer create-project laravel/laravel example-appStep 2 : Create New Migration
create migration table using Laravel 9 php artisan command, so first fire bellow command:
php artisan make:migration create_files_tabledatabase/migrations/create_files_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('files', function (Blueprint $table) { $table->id(); $table->string('file'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('files'); } };
now, we need to run migration command to create database table:
php artisan migrateStep 3 : Create New Model
Here, we already have table created, so we need create model run command to create model:
php artisan make:model Fileapp/Models/File.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class File extends Model { use HasFactory; protected $fillable = [ 'file', ]; }Step 4 : Create New Controller
In this second step, we need to create a new FileUploadController; in this file, we will add two method index() and store() for render view and store image logic.
Let's create FileUploadController by following command:
php artisan make:controller FileUploadControllerapp/Http/Controllers/FileUploadController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\File; class FileUploadController extends Controller { /** * Write Your Code.. * * @return string */ public function index() { return view('index'); } /** * Write Your Code.. * * @return string */ public function store(Request $request) { request()->validate([ 'file' => 'required|mimes:pdf,csv,txt,xlx,xls|max:2048', ]); if ($files = $request->file('file')) { $filename = request()->file->getClientOriginalName(); $file = $request->file->move(public_path('files'), $filename); $document = new File(); $document->file = $filename; $document->save(); return Response()->json([ "success" => true, "file" => $file ]); } return Response()->json([ "success" => false, "file" => '' ]); } }Step 5 : Create Routes routes/web.php
<?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::get('/file',[FileUploadController::class, 'index']); Route::post('upload-file',[FileUploadController::class, 'store'])->name('file.store');Step 6: Create Blade File resources/views/index.blade.php
<!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 9 File Upload using Ajax Example Tutorial</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> </head> <body> <div class="container mt-5 pt-5"> <div class="row d-flex justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header bg-success text-white"> <h4 class="text-center">Laravel 9 File Upload using Ajax Example Tutorial - Tuts-Station.com</h4> </div> <div class="card-body"> <div class="alert alert-success alert-dismissible fade show successAlert" style="display:none;" role="alert"> File has been uploaded successfully <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> <form method="POST" enctype="multipart/form-data" id="laravel-ajax-file-upload" action="javascript:void(0)" > <div class="mt-3"> <label>Select File : <span class="text-danger">*</span></label> <input type="file" name="file" placeholder="Choose File" id="file" class="form-control"> <span class="text-danger" id="error"></span> </div> <div class="text-center mt-3"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> </div> </div> </div> </div> </div> </body> <script type="text/javascript"> $(document).ready(function (e) { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); /*------------------------------------------ -------------------------------------------- File Upload -------------------------------------------- --------------------------------------------*/ $('#laravel-ajax-file-upload').submit(function(e) { e.preventDefault(); var formData = new FormData(this); $.ajax({ type:'POST', url: "{{ route('file.store')}}", data: formData, cache:false, contentType: false, processData: false, success: (data) => { this.reset(); $('.successAlert').css('display','block'); }, error: function(data){ $('#error').text(data.responseJSON.message); } }); }); }); </script> </html>Run Laravel App:
All steps have been done, now you have to type the given command and hit enter to run the laravel app:
php artisan serveOutput :

I hope it can help you...