1. Masuk App lalu buat folder "Traits"

2. Setelah membuat folder Traits lalu buat file bernama FileUpload.php

3. lalu pastekan code ini pada file FileUpload.php

<?php

namespace App\Traits;
use Illuminate\Support\Facades\Storage;

trait FileUpload
{

// Function Untuk Menambah File
public function tambahFile($model, $column, $name, $path)
{
if ($this->$column) {
$namaFile = $name . now()->format('YmdHis') . '.' . $this->$column->extension();
$this->$column->storeAs($path, $namaFile);
$model->$column = $namaFile;
}
}

// Function Untuk Update File
public function updateFile($model, $column, $name, $path)
{
if ($this->$column != $model->$column) {

if (!is_null($model->$column)) {
Storage::delete($path . '/' . $model->$column);
}

if ($this->$column) {
$namaFile = $name . now()->format('YmdHis') . '.' . $this->$column->extension();
$this->$column->storeAs($path, $namaFile);
$model->$column = $namaFile;
}

$this->reset([$column]);
}
}

// Function Untuk Menghapus File
public function hapusFile($model, $column, $path)
{
if (!is_null($model->$column)) {
Storage::delete($path . '/' . $model->$column);
}
}

}

4. Jika sudah masuk ke componen yang akan memakan upload file berikut penerapan masing" fungsi

*store

Penjelasan :

//Parameneter tambahFile  (1. nama Model (variabel), 2. nama colum (string), 3. nama file (string), 4. lokasi simpan file (string))

contoh :


// Untuk mengupload file
$this->tambahFile($sekolah, 'file', 'sekolah', 'fileFolder');

*Update

Penjelasan :

//Parameneter updateFile  (1. nama Model (variabel), 2. nama colum (string), 3. nama file (string), 4. lokasi simpan file (string))

contoh :

// Untuk Mengupdate file
$this->updateFile($sekolah, 'file', 'sekolah', 'fileFolder');

*Delete

Penjelasan :

//Parameneter hapusFile  (1. nama Model (variabel), 2. nama colum (string),  3. lokasi simpan file (string))

contoh :

// untuk menghapus gambar
$this->hapusFile($sekolah, 'file', 'fileFolder');