62 lines
1.3 KiB
PHP
62 lines
1.3 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Illuminate\Support\Str;
|
|
|
|
class File extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
protected $fillable = [
|
|
'fileable_type',
|
|
'fileable_id',
|
|
'type',
|
|
'name',
|
|
'extension',
|
|
'path',
|
|
];
|
|
|
|
protected $appends = [
|
|
'url'
|
|
];
|
|
|
|
public static $file_directories = [
|
|
'import-temp' => 'import-temp/',
|
|
];
|
|
|
|
public function fileable()
|
|
{
|
|
return $this->morphTo();
|
|
}
|
|
|
|
public function getUrlAttribute()
|
|
{
|
|
return Storage::url($this->path);
|
|
}
|
|
|
|
public function getDirectory($type)
|
|
{
|
|
return self::$file_directories[$type] ?? 'any';
|
|
}
|
|
|
|
public static function getFileName($type, $id, $file)
|
|
{
|
|
$extension = $file->getClientOriginalExtension();
|
|
|
|
return $type . '-' . $id .'-'.Str::random(10).'.'.$extension;
|
|
}
|
|
|
|
public static function storeFile($type, $id, $file)
|
|
{
|
|
$fileName = self::getFileName($type, $id, $file);
|
|
$directory = self::getDirectory($type);
|
|
$path = $directory . $fileName;
|
|
$file->storeAs($directory, $fileName);
|
|
return $path;
|
|
}
|
|
}
|