first init
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
namespace App\Traits;
|
||||
|
||||
use App\Models\Document;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
|
||||
trait HasDocuments
|
||||
{
|
||||
/**
|
||||
* Get all documents for this model.
|
||||
*/
|
||||
public function documents()
|
||||
{
|
||||
return $this->morphMany(Document::class, 'documentable');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get documents of a specific type.
|
||||
*/
|
||||
public function documentsOfType($type)
|
||||
{
|
||||
return $this->documents()->where('document_type', $type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload a document for this model.
|
||||
*/
|
||||
public function uploadDocument(UploadedFile $file, $documentType = 'general', $description = null)
|
||||
{
|
||||
// Generate unique filename
|
||||
$fileName = time().'_'.$file->getClientOriginalName();
|
||||
|
||||
// Store file in a folder named after the model
|
||||
$folderName = strtolower(class_basename($this));
|
||||
$filePath = $file->storeAs("documents/{$folderName}", $fileName);
|
||||
|
||||
// Create document record
|
||||
return $this->documents()->create([
|
||||
'document_name' => $file->getClientOriginalName(),
|
||||
'document_path' => $filePath,
|
||||
'file_size' => $file->getSize(),
|
||||
'mime_type' => $file->getClientMimeType(),
|
||||
'document_type' => $documentType,
|
||||
'description' => $description,
|
||||
'uploaded_by' => auth()->id(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a document by ID.
|
||||
*/
|
||||
public function deleteDocument($documentId)
|
||||
{
|
||||
$document = $this->documents()->findOrFail($documentId);
|
||||
|
||||
return $document->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get documents count.
|
||||
*/
|
||||
public function getDocumentsCountAttribute()
|
||||
{
|
||||
return $this->documents()->count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get documents count by type.
|
||||
*/
|
||||
public function getDocumentsCountByType($type)
|
||||
{
|
||||
return $this->documentsOfType($type)->count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if model has documents.
|
||||
*/
|
||||
public function hasDocuments()
|
||||
{
|
||||
return $this->documents()->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if model has documents of specific type.
|
||||
*/
|
||||
public function hasDocumentsOfType($type)
|
||||
{
|
||||
return $this->documentsOfType($type)->exists();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user