How to Upload File and Generate UUID in Laravel

How to Upload File and Generate UUID in Laravel

 Hello Dev,

In this tutorial, I will show you step-by-step how to upload files in Laravel 9 and automatically generate a UUID for each uploaded file. This is very useful when you want to uniquely identify uploaded files instead of only using their original names.

We’ll build a simple File Upload form in Laravel 9 where every file gets stored with a UUID in the database.

Step 1: Create a Fresh Laravel Project

First, create a new Laravel 9 project or use an existing one.

composer create-project laravel/laravel laravel-file-upload-uuid cd laravel-file-upload-uuid php artisan serve

Step 2: Create Migration for File Uploads

Run the following command to create a migration file:

php artisan make:migration create_file_uploads_table

Now, open the migration file and update it as follows:

<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up(): void { Schema::create('file_uploads', function (Blueprint $table) { $table->id(); $table->string('upload_by')->nullable(); $table->string('date_time')->nullable(); $table->string('file_name')->nullable(); $table->uuid('uuid')->unique(); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('file_uploads'); } };

Run migration:

php artisan migrate

Step 3: Create Model

Generate a model for file uploads:

php artisan make:model FileUpload

Step 4: Create Controller

Generate a controller:

php artisan make:controller FormController

Update app/Http/Controllers/FormController.php:

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; use Carbon\Carbon; use App\Models\FileUpload; use Brian2694\Toastr\Facades\Toastr; class FormController extends Controller { /** Show upload form */ public function formUploadIndex() { return view('form.form-upload-file'); } /** Handle file upload */ public function formFileUpdate(Request $request) { $request->validate([ 'upload_by' => 'required|string|max:255', 'file_name' => 'required', ]); DB::beginTransaction(); try { $dt = Carbon::now(); $date_time = $dt->toDayDateTimeString(); $folder_name = "file_store"; Storage::disk('local')->makeDirectory($folder_name, 0775, true); if ($request->hasFile('file_name')) { foreach ($request->file_name as $photos) { $file_name = $photos->getClientOriginalName(); $saveRecord = new FileUpload; $saveRecord->upload_by = $request->upload_by; $saveRecord->date_time = $date_time; $saveRecord->file_name = $file_name; $saveRecord->uuid = Str::uuid(); // Generate UUID Storage::disk('local')->put($folder_name.'/'.$file_name, file_get_contents($photos->getRealPath())); $saveRecord->save(); } DB::commit(); Toastr::success('File uploaded successfully :)','Success'); return redirect()->back(); } } catch(\Exception $e) { DB::rollback(); Toastr::error('File upload failed :)','Error'); return redirect()->back(); } } }

Step 5: Define Routes

Open routes/web.php:

use Illuminate\Support\Facades\Route; use App\Http\Controllers\FormController; Route::get('form/upload', [FormController::class, 'formUploadIndex'])->name('form/upload'); Route::post('form/upload/file', [FormController::class, 'formFileUpdate'])->name('form/upload/file');

Step 6: Create Blade View

Create a file at:
resources/views/form/form-upload-file.blade.php

@extends('layouts.master') @section('content') {!! Toastr::message() !!} <div class="container mt-5"> <h3 class="text-center">File Upload with UUID</h3> <form action="{{ route('form/upload/file') }}" method="POST" enctype="multipart/form-data"> @csrf <div class="mb-3"> <input type="text" name="upload_by" class="form-control" placeholder="Upload by" required> </div> <div class="mb-3"> <input type="file" name="file_name[]" class="form-control" multiple required> </div> <button type="submit" class="btn btn-primary">Upload</button> </form> </div> @endsection

Step 7: Run the Application

Start your Laravel server:

php artisan serve

Visit:
👉 http://127.0.0.1:8000/form/upload

Upload a file, and each record will be saved in the database with a unique UUID. 🎉

Souy Soeng

Souy Soeng

Hi there 👋, I’m Soeng Souy (StarCode Kh)
-------------------------------------------
🌱 I’m currently creating a sample Laravel and React Vue Livewire
👯 I’m looking to collaborate on open-source PHP & JavaScript projects
💬 Ask me about Laravel, MySQL, or Flutter
⚡ Fun fact: I love turning ☕️ into code!

Post a Comment

CAN FEEDBACK
close