cyber-duck/model-files

为Eloquent模型提供HasFiles特性

dev-master 2021-10-26 09:24 UTC

This package is auto-updated.

Last update: 2024-08-26 16:03:06 UTC


README

请考虑使用Spatie Media Library代替。

模型文件

这仍在开发中,因为它是从现有项目中提取出来的,所以一些功能仍在开发中并有所变动。

测试被链接到多个模型(将很快移除)。

作者: Tiago Tavares

Cyber-Duck Ltd用❤️制作

简介

模型文件提供了一个简单的特性(HasFiles),可以在您的eloquent模型中使用。

这个特性允许您通过数组在模型中定义一个简单的存储配置

  • 一个观察者将处理磁盘上存在的文件的存储和修剪。
  • 另一个特性用于与存储外观交互的方法。

安装

composer require cyber-duck/model-files --dev

用法

存储/保存,例如从您的控制器之一

...
public function store(Request $request, Company $company) {
    $validatedData = $request->validate([
        'logo' => 'required|image',
    ]);
    
    // You can set logo to a string (if it's already stored in the disk)
    // If won't create another file
    $company->logo = $validatedData->logo;
    $company->save();
    
    ...
}

访问文件URL

Company::find(1)->url('logo');

删除文件

$company = Company::find(1);
$company->deleteFile('logo'); // Deletes and sets the attribute to `null`
$company->save();

@todo 删除模型也会修剪文件

Company::find(1)->delete(); // File will be deleted as well

### 配置

让您的模型实现Storable接口,并使用特性HasFiles到您的模型类。

<?php

namespace App;

use Cyberduck\ModelFiles\Storable;
use Cyberduck\ModelFiles\HasFiles;
use Illuminate\Database\Eloquent\Model;

class Company extends Model implements Storable
{
    use HasFiles;
}

在模型上定义您的文件

class Company extends Model implements Storable
{
    ...
    
    protected $files = [
        'logo' => [
            'disk' => 'public', // Default is 'default'
            'folder' => 'logos', // Default is '/'
            'prunable' => true, // Default is true
        ],
        'avatar' => [
            'disk' => 'public',
            'folder' => 'avatars',
            'url' => 'temporary', // available: 'public' (default), 'temporary', 'custom'
            'expiresAt' => '+5 min', (Not implemented yet - for temporary)
        ],
        'invoice' => [
            'folder' => 'invoices',
            'url' => 'custom', // The following method will be called: `getUrlInvoice` with the value of the attribute
        ]
    ];
    
    public function getUrlInvoice($path) {
        // e.g. `companies/1/invoices/randomGenerated.pdf`
        return route('company.invoice', [$company, $path]);
    }