|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Adminetic\Website\Traits; |
|
4
|
|
|
|
|
5
|
|
|
use Carbon\Carbon; |
|
6
|
|
|
use Illuminate\Support\Facades\File; |
|
7
|
|
|
use Illuminate\Support\Facades\Storage; |
|
8
|
|
|
|
|
9
|
|
|
trait HasFileUpload |
|
10
|
|
|
{ |
|
11
|
|
|
public function fileUpload($file, $directory, $given_name = null) |
|
12
|
|
|
{ |
|
13
|
|
|
if (! $file->isValid()) { |
|
14
|
|
|
throw new \Exception('File was not uploaded successfully'); |
|
15
|
|
|
} |
|
16
|
|
|
|
|
17
|
|
|
/** Check if folder exits or not. If not then create the folder */ |
|
18
|
|
|
if (! File::exists(storage_path($directory))) { |
|
19
|
|
|
File::makeDirectory(storage_path($directory), 0775, true); |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
$original_name = strtolower(str_replace([' ', '-', '$', '<', '>', '&', '{', '}', '*', '\\', '/', ':', '.', ';', ',', "'", '"'], '_', trim($given_name ?? pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)))); |
|
|
|
|
|
|
23
|
|
|
$timestamp = Carbon::now()->toDateString(); |
|
24
|
|
|
$extension = $file->getClientOriginalExtension(); |
|
25
|
|
|
$size = $file->getSize(); |
|
26
|
|
|
$name = str_replace(' ', '', $original_name.'-'.Carbon::now()->toDateString().'-'.$size.'.'.$file->getClientOriginalExtension()); |
|
27
|
|
|
|
|
28
|
|
|
$disk = config('filesystems.default', 'public'); |
|
29
|
|
|
|
|
30
|
|
|
$path = null; |
|
31
|
|
|
if ($disk == 'public') { |
|
32
|
|
|
$path = $file->storeAs($directory, $name, 'public'); |
|
33
|
|
|
} else { |
|
34
|
|
|
$path = Storage::disk($disk)->putFileAs( |
|
35
|
|
|
$directory, |
|
36
|
|
|
$file, |
|
37
|
|
|
$name |
|
38
|
|
|
); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
return json_decode(json_encode([ |
|
42
|
|
|
'original_name' => $original_name ?? null, |
|
43
|
|
|
'timestamp' => $timestamp ?? null, |
|
44
|
|
|
'extension' => $extension ?? null, |
|
45
|
|
|
'size' => $size ?? null, |
|
46
|
|
|
'name' => $name ?? null, |
|
47
|
|
|
'path' => $path ?? null, |
|
48
|
|
|
])); |
|
49
|
|
|
} |
|
50
|
|
|
} |
|
51
|
|
|
|