File Upload using Ajax in Laravel 10

1. Create a form with a file input field

@csrf


2. Create a route to handle the file upload

Route::post(‘/upload’, ‘FileController@upload’)->name(‘upload’);

3. Create a controller to handle the file upload

hasFile(‘file’)) {
$file = $request->file(‘file’);
// Get the file name
$filename = $file->getClientOriginalName();
// Move the file to the desired location
$file->move(public_path(‘uploads’), $filename);
}
return response()->json([‘success’ => true]);
}
}

4. Create an Ajax request to handle the file upload

$.ajax({
url: “{{ route(‘upload’) }}”,
type: ‘POST’,
data: new FormData($(‘form’)[0]),
contentType: false,
processData: false,
success: function(data) {
if (data.success) {
alert(‘File uploaded successfully!’);
}
}
});
[ad_1]

Sometimes, you need to upload files without page refresh in your laravel web application. So, In this tutorial, you will learn how to upload files using jquery Ajax in laravel 10 apps.

How to Upload File using Ajax In Laravel 10

By following these steps, you can implement ajax jquery file like pdf, excel, CSV, etc upload in laravel 10 apps.

  • 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

[ad_2]

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

GSTIN is 03EGRPS4248R1ZD.

Contact
Jassweb, Rai Chak, Punjab, India. 143518
Item added to cart.
0 items - 0.00