Logo

dev-resources.site

for different kinds of informations.

How To Upload Multiple File In Laravel 10

Published at
3/29/2024
Categories
laravel
php
upload
file
Author
techsolutionstuff
Categories
4 categories in total
laravel
open
php
open
upload
open
file
open
Author
17 person written this
techsolutionstuff
open
How To Upload Multiple File In Laravel 10

​
In this article, we will see how to upload multiple files in laravel 10.

Here, we will learn about multiple file uploads with validation in laravel 10 and laravel 11.

You can select at a time multiple file documents to upload. Also, you can validate file types and maximum file upload size in laravel 10/11.

In laravel 11, you can upload multiple files with validation. We'll check the validation when uploading the file for file type and max file size.

So, let's see laravel 10 multiple file upload, multiple file upload in laravel 10 and laravel 11, multiple file validation in laravel 10/11, and upload multiple files with validation in laravel 10/11.

Step 1: Install Laravel 10/11

Step 2: Create Migration and Model

Step 3: Create FileController

Step 4: Add Routes

Step 5: Create Blade File

Step 6: Run Laravel 10 Application
Enter fullscreen mode Exit fullscreen mode

 

Step 1: Install Laravel 10/11

In this step, we will install laravel 10 using the following command.

composer create-project laravel/laravel laravel_10_multiple_file_upload_example
Enter fullscreen mode Exit fullscreen mode

 

Step 2: Create Migration and Model

Now, we will create migration and model using the following command.

php artisan make:migration create_files_table
Enter fullscreen mode Exit fullscreen mode

Migration:

<?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('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('files');
    }
};
Enter fullscreen mode Exit fullscreen mode

After that, we will migrate the table to the database using the following command.

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Now, we will create a File model using the following command.

php artisan make:model File
Enter fullscreen mode Exit fullscreen mode

app/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 = [
        'name'
    ];
}
Enter fullscreen mode Exit fullscreen mode

  
Step 3: Create FileController

In this step, we will create FileController using the following artisan command. So, add the below code to that file to upload multiple file upload in laravel 10.

php artisan make:controller FileController
Enter fullscreen mode Exit fullscreen mode

app/Http/Controllers/FileController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\File;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;

class FileController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(): View
    {
        return view('index');
    }  

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'files' => 'required',
            'files.*' => 'required|mimes:pdf,xlx,csv|max:2048',
        ]);

        $files = [];
        if ($request->file('files')){
            foreach($request->file('files') as $key => $file)
            {
                $file_name = time().rand(1,99).'.'.$file->extension();  
                $file->move(public_path('uploads'), $file_name);
                $files[]['name'] = $file_name;
            }
        }

        foreach ($files as $key => $file) {
            File::create($file);
        }

        return back()->with('success','File uploaded successfully');

    }
}
Enter fullscreen mode Exit fullscreen mode

 

Step 4: Add Routes

Now, we will add routes to the web.php file. So, add the below code to that file for GET and POST requests.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\FileController;

/* 
|--------------------------------------------------------------------------
| 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(FileController::class)->group(function(){
    Route::get('index', 'index');
    Route::post('store', 'store')->name('file.store');
});
Enter fullscreen mode Exit fullscreen mode

 

Step 5: Create Blade File

In this step, we will create an index.blade.php file. So, add the HTML code to that file to upload multiple files.

resources/views/index.blade.php

<!DOCTYPE html>
<html>
    <head>
        <title>How To Upload Multiple File In Laravel 10/11 - Techsolutionstuff</title>
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>      
    <body>
        <div class="container">            
            <div class="panel panel-primary">        
                <div class="panel-heading">
                    <h2>How To Upload Multiple File In Laravel 10/11 - Techsolutionstuff</h2>
                </div>        
                <div class="panel-body">                
                    @if ($message = Session::get('success'))
                        <div class="alert alert-success alert-block">
                            <strong>{{ $message }}</strong>
                        </div>
                    @endif

                    <form action="{{ route('file.store') }}" method="POST" enctype="multipart/form-data">
                        @csrf            
                        <div class="mb-3">
                            <label class="form-label">Select Files:</label>
                            <input type="file" name="files[]" multiple class="form-control @error('files') is-invalid @enderror">

                            @error('files')
                                <span class="text-danger">{{ $message }}</span>
                            @enderror
                        </div>            
                        <div class="mb-3">
                            <button type="submit" class="btn btn-success">Upload</button>
                        </div>                
                    </form>                
                </div>
            </div>
        </div>
    </body>    
</html>
Enter fullscreen mode Exit fullscreen mode


 

Step 6: Run Laravel 10 Application

Now, we will run laravel 10 multiple file uploads with validation using the following command.

php artisan serve
Enter fullscreen mode Exit fullscreen mode

You might also like:

Read Also: How To File Upload Using Node.js

upload Article's
30 articles in total
Favicon
UploadThing: A Modern File Upload Solution for Next.js Applications
Favicon
NestJS - Armazenamento nas nuvens
Favicon
NestJS - criar um endpoint para upload de diversos arquivos
Favicon
NestJS - Validando o envio de arquivos
Favicon
NestJS - Armazenamento local de upload
Favicon
NestJS - criar endpoint para upload de 1 arquivo
Favicon
Next.js: Upload de imagem para a Cloudflare R2 Utilizando Presigned URL
Favicon
A file uploader built with shadcn/ui and react-dropzone
Favicon
Elevate Your GraphQL API: Mastering File Uploads with Yoga GraphQL
Favicon
Mastering File Uploads in Laravel 11: A Comprehensive Guide
Favicon
How To Upload Multiple File In Laravel 10
Favicon
Different approaches to reduce AWS S3 file upload time using AWS-SDK v3 in NodeJS.
Favicon
How would you handle image upload?
Favicon
Upload File di Node JS
Favicon
Uploading Images with Node.js and React.js
Favicon
Simplifying AWS S3 File Uploads with the Android Library
Favicon
Laravel 10 Crop Image Before Upload Cropper Js
Favicon
Enhance Job Seeker Experience: Quick Image Upload for Portals
Favicon
A file upload sample with NextJs
Favicon
Azure Storage Account: Unleash the Potential of Cloud-Based Storage
Favicon
Spheron Network: Browser Upload
Favicon
Uploading files from terminal on file hosting service, and unlimited cloud storage
Favicon
Process FormData file sent to Node server
Favicon
Express file upload using Multer
Favicon
Maximize Your Client Upload Efficiency with the Bulk Upload
Favicon
Upload images in Ckeditor 5 with Laravel
Favicon
Eteot Logo
Favicon
Install & Upload WordPress Plugin
Favicon
Laravel 9 Multiple Image Upload Example
Favicon
How To Enhance JavaScript File Upload In Your Web App

Featured ones: