Dynamically create a new folder when uploading file

Dynamically create a new folder when uploading file

Step 1: Update Your Database Credentials

Open the .env file in the root of your Laravel project and update the database connection info like this:

DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel_learn DB_USERNAME=root DB_PASSWORD=

⚠️ Make sure the database laravel_learn exists in your MySQL server.

Then run:

php artisan config:cache

Step 2: File Upload Form (Blade View)

Create a Blade file at resources/views/form.blade.php and paste the following code:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Form</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:400,700"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> <style> body { color: #999; background: #f5f5f5; font-family: 'Roboto', sans-serif; } .signup-form { width: 50%; margin: 0 auto; padding: 30px 0; } .signup-form form { background: #fff; padding: 30px; border-radius: 1px; border: 1px solid #f3f3f3; box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); } .signup-form h2 { margin: 0 0 15px; text-align: center; } .form-control { min-height: 38px; box-shadow: none !important; border-width: 0 0 1px 0; } .btn { font-size: 16px; font-weight: bold; background: #19aa8d; border: none; min-width: 140px; } .btn:hover { background: #179b81; } </style> </head> <body> <div class="signup-form"> <form action="{{ route('form/save') }}" method="POST" enctype="multipart/form-data"> @csrf <h2>Create Form File Upload</h2> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-cloud-upload"></i></span> <input type="file" class="form-control" name="fileupload[]" required multiple> </div> </div> <div class="form-group"> <button type="submit" class="btn btn-primary btn-block">Save</button> </div> </form> </div> </body> </html>

Step 3: Create Controller

Run the following command to create a controller:

php artisan make:controller FormController

Now, update the controller (app/Http/Controllers/FormController.php) with this code:

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; use Carbon\Carbon; class FormController extends Controller { public function index() { return view('form'); } public function saveRecord(Request $request) { $dt = Carbon::now(); $folder_name = 'upload'; $date_time = $dt->toDayDateTimeString(); \Storage::disk('local')->makeDirectory($folder_name, 0775, true); if ($request->hasFile('fileupload')) { foreach ($request->fileupload as $photo) { $file_name = $photo->getClientOriginalName(); $path = $folder_name . '/' . $file_name; // Save to storage \Storage::disk('local')->put($path, file_get_contents($photo->getRealPath())); // Insert into DB DB::table('uplaod_tbl')->insert([ 'file_name' => $file_name, 'path' => $path, 'datetime' => $date_time, 'created_at' => now(), 'updated_at' => now(), ]); } } return redirect()->back()->with('success', 'Files uploaded successfully.'); } }

Step 4: Define Routes

Open routes/web.php and add these routes:

use Illuminate\Support\Facades\Route; use App\Http\Controllers\FormController; Route::get('/', function () { return redirect('form/new'); }); Route::get('form/new', [FormController::class, 'index'])->name('form/new'); Route::post('form/save', [FormController::class, 'saveRecord'])->name('form/save');

Step 5: Create Migration

Create a migration file:

php artisan make:migration create_uplaod_tbl_table

Edit the migration (database/migrations/xxxx_xx_xx_create_uplaod_tbl_table.php):

<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUplaodTblTable extends Migration { public function up() { Schema::create('uplaod_tbl', function (Blueprint $table) { $table->id(); $table->string('file_name')->nullable(); $table->string('path')->nullable(); $table->string('datetime')->nullable(); $table->timestamps(); }); } public function down() { Schema::dropIfExists('uplaod_tbl'); } }

🔧 Note: The table name uplaod_tbl has a typo. It's better to use upload_tbl, but if you're sticking with the current name, just be consistent.

Step 6: Migrate the Table

Run the migration:

php artisan migrate

Step 7: Run the Laravel App

Start the local server:

php artisan serve

Open your browser and go to:

http://127.0.0.1:8000

You'll see your file upload form ready to use.

Let me know if you want to:

  • Store files in public/ instead of storage/app/

  • Show uploaded files below the form

  • Enable downloading or deleting files

  • Use an Eloquent model instead of DB facade

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close