Skip to content

Commit 44508b6

Browse files
can get and delete attachments 📁
1 parent 5169c3c commit 44508b6

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

src/Attachmentable.php

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,22 @@ public function attachments()
1212
return $this->morphMany(Attachment::class, 'attachmentable');
1313
}
1414

15+
/**
16+
* @return bool
17+
*/
18+
public function checkIfExists($attachments): bool
19+
{
20+
return $attachments->exists();
21+
}
22+
23+
/**
24+
* @param $files,$dirName
25+
* @return bool
26+
*/
1527
public function newAttach($file, $dirName = 'public')
1628
{
1729
if (isset($file)) {
18-
$fileName = md5(time()).'.'.$file->extension();
30+
$fileName = md5(time().rand(0, 1000000)).'.'.$file->extension();
1931
Storage::disk('public')->putFileAs(
2032
$dirName,
2133
$file,
@@ -29,10 +41,41 @@ public function newAttach($file, $dirName = 'public')
2941
}
3042
}
3143

44+
/**
45+
* @param $files
46+
* @return bool
47+
*/
3248
public function newAttachs($files, $dirName = 'public')
3349
{
3450
foreach ($files as $file) {
3551
$this->newAttach($file, $dirName);
3652
}
3753
}
54+
55+
/**
56+
* @return array
57+
*/
58+
public function getAttachs()
59+
{
60+
if ($this->checkIfExists($this->attachments())) {
61+
return $this->attachments()->pluck('name');
62+
};
63+
}
64+
65+
/**
66+
* @param $dirName string
67+
* @return bool
68+
*/
69+
public function deleteAttach($dirName = 'public')
70+
{
71+
$fileExists = Storage::disk('public')->exists(ltrim($dirName."/".$this->attachments()->first()->name));
72+
if (!$fileExists) {
73+
return 'this attachment does not exists in this dir '.$dirName;
74+
}
75+
if ($this->checkIfExists($this->attachments())) {
76+
Storage::disk('public')->delete(ltrim($dirName."/".$this->attachments()->first()->name));
77+
$this->attachments()->first()->delete();
78+
return 'attachment has deleted successfuly';
79+
}
80+
}
3881
}

0 commit comments

Comments
 (0)