How to upload file and with generate uuid Laravel 9

How to upload file and with generate uuid Laravel 9

     

Admin dashboard in Laravel 9 | Sample Template

Hello Dev,

This tutorial will give you an example of how to clone a Laravel project from GitHub. let’s discuss the steps to clone the Laravel project from GitHub. I explained simply about the clone Laravel project from GitHub. This article goes into detail on the clone Laravel project from Github on the server.

In this tutorial, I will show you step-by-step how to clone laravel projects from Github, GitLab, or bitbucket and set up an ubuntu server from scratch. you can easily clone laravel 6, laravel 7, laravel 8, and laravel 9 projects from this post.

So, let's follow the below step-by-step and get done with the clone laravel app.

'

Git Clone my Project

1.Run `git clone 'link projer github'
2.Run composer update
3.Run cp .env.example .env or copy .env.example .env
4.Run php artisan key:generate
5.Run php artisan migrate
6.Run php artisan serve
7.Go to link localhost:8000

Step 1: Git Clone Laravel 9

First, clone a new Laravel app just by running the below command in your terminal.

git clone https://gitlab.com/SoengSouy/admin-dashboard-sample-laravel-9.git

Step 2: Composer Update

Type the command in your terminal.

composer update

Step 3: Set active on the route

Type the command in your terminal.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\FormController;

/*
|--------------------------------------------------------------------------
| 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!
|
*/

/** set active side bar */
function set_active($route) {
    if (is_array($route)) {
        return in_array(Request::path(), $route) ? 'active' : '';
    }
    return Request::path() == $route ? 'active' : '';
}

Route::get('/', function () {
    return view('dashboard.dashboard');
})->name('/');

// ----------------------------- main dashboard ------------------------------//
Route::controller(HomeController::class)->group(function () {
    Route::get('dashboard/page', 'index')->name('dashboard/page');
    Route::get('form/input', 'index')->name('form/input');
});
// -------------------------------- form ------------------------------------//
Route::controller(FormController::class)->group(function () {
    Route::post('form/upload/file', 'formFileUpdate')->name('form/upload/file'); // file upload
});

Step 4: Form

views/form/form-upload-file.blade.php

@extends('layouts.master')
@section('content')
@section('style')
<style>
    .btn-tertiary {
        color: #555;
        padding: 0;
        line-height: 40px;
        width: 300px;
        margin: auto;
        display: block;
        border: 2px solid #555;
    }
    .btn-tertiary:hover, .btn-tertiary:focus {
        color: #888888;
        border-color: #888888;
    }

    /* input file style */
    .input-file {
        width: 0.1px;
        height: 0.1px;
        opacity: 0;
        overflow: hidden;
        position: absolute;
        z-index: -1;
    }
    .input-file + .js-labelFile {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        padding: 0 10px;
        cursor: pointer;
    }
    .input-file + .js-labelFile .icon:before {
        content: "";
    }
    .input-file + .js-labelFile.has-file .icon:before {
        content: "";
        color: #5AAC7B;
    }
</style>

@endsection
    {{-- message --}}
    {!! Toastr::message() !!}
    <div class="page-wrapper">
        <div class="content container-fluid">
            <div class="page-header">
                <div class="row">
                    <div class="col-sm-12">
                        <h3 class="page-title">File Upload</h3>
                        <ul class="breadcrumb">
                            <li class="breadcrumb-item"><a href="{{ route('/') }}">Dashboard</a></li>
                            <li class="breadcrumb-item active">File Upload</li>
                        </ul>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header" style="text-align: center;">
                            <h5 class="card-title mb-0">File Upload</h5>
                        </div>
                        <br>
                        <form action="{{ route('form/upload/file') }}" id="file-upload-form" class="uploader" method="POST" enctype="multipart/form-data">
                            @csrf
                            <div class="form-group">
                                <div class="col-xl-12">
                                    <div class="form-group">
                                        <input type="text" class="form-control @error('upload_by') is-invalid @enderror" name="upload_by" placeholder="Upload by" value="{{ old('upload_by') }}">
                                    </div>
                                </div> 
                                <input type="file" name="file_name[]" id="file" class="input-file @error('file_name[]') is-invalid @enderror" multiple>
                                <label for="file" class="btn btn-tertiary js-labelFile">
                                    <i class="icon fa fa-check"></i>
                                    <span class="js-fileName">Choose a file</span>
                                </label>
                            </div>
                            <div class="text-center">
                                <button type="submit" class="btn btn-primary">Submit</button>
                            </div>
                            <br>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    @section('script')
    <script>
        (function() {
            $('.input-file').each(function() {
                var $input = $(this),
                $label = $input.next('.js-labelFile'),
                labelVal = $label.html();
                $input.on('change', function(element) {
                    var fileName = '';
                    if (element.target.value) fileName = element.target.value.split('\\').pop();
                    fileName ? $label.addClass('has-file').find('.js-fileName').html(fileName) : $label.removeClass('has-file').html(labelVal);
                });
            });
        })();
    </script>
@endsection
@endsection

Step 5: Controller

app\Http\Controllers\FormController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use Uuid;
use Carbon\Carbon;
use App\Models\FormInput;
use App\Models\FileUpload;
use Brian2694\Toastr\Facades\Toastr;

class FormController extends Controller
{
    /** form upload file index */
    public function formUpdateIndex()
    {
        return view('form.form-upload-file');
    }
    /** update file */
    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); // create directory
            if($request->hasFile('file_name'))
            {
                foreach($request->file_name as $photos) {
                    $file_name = $photos->getClientOriginalName(); // get file original name
                    $saveRecord = new FileUpload;
                    $saveRecord->upload_by = $request->upload_by;
                    $saveRecord->date_time = $date_time;
                    $saveRecord->file_name = $file_name;
                    $saveRecord->uuid = Uuid::generate(5,$date_time . $file_name .$folder_name, Uuid::NS_DNS);
                    \Storage::disk('local')->put($folder_name.'/'.$file_name,file_get_contents($photos->getRealPath()));
                    $saveRecord->save();
                }
                DB::commit();
                Toastr::success('Data has been saved successfully :)','Success');
                return redirect()->back();
            }
        } catch(\Exception $e) {
            DB::rollback();
            Toastr::error('Data save fail :)','Error');
            return redirect()->back();
        }
    }
}

Step 6: Migrate the table

Type the command in your terminal.

<?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('file_uploads', function (Blueprint $table) {
            $table->id();
            $table->string('upload_by')->nullable();
            $table->string('date_time')->nullable();
            $table->string('file_name')->nullable();
            $table->string('uuid')->nullable();
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('file_uploads');
    }
};

php artisan migrate

Step 5:Run

After adding the run file now run the migrate command.

php artisan serve

StarCode Kh

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

Post a Comment

Previous Post Next Post
close