brysem/eloquent-files

为模型轻松管理文件的开源文件。

v1.0.0 2017-02-04 02:05 UTC

This package is not auto-updated.

Last update: 2024-09-15 02:01:11 UTC


README

Packagist License Latest Stable Version Total Downloads

这是一个方便上传和附加文件到eloquent模型的包。它包括一个ServiceProvider来发布迁移。文件上传将由您的默认文件系统存储处理。这可以在filesystem.php配置中更改。当删除包含文件的模型时,文件也会自动删除。

安装

使用composer要求此包

composer require brysem/eloquent-files

更新composer后,将ServiceProvider添加到config/app.php中的providers数组中。

Bryse\Eloquent\Files\FilesServiceProvider::class,

使用发布命令将包迁移复制到您的本地迁移文件夹

php artisan vendor:publish --provider="Bryse\Eloquent\Files\FilesServiceProvider" --tag="migrations"

HasFiles特质添加到您想要保存文件的eloquent模型中。

use Bryse\Eloquent\Files\Traits\HasFiles;

class User extends Authenticatable
{
    use HasFiles;
}

用法

您现在可以轻松处理文件上传并将它们保存到eloquent模型中。

// Returns an array of the files that have been uploaded.
// The second parameter is the path inside your storage_path().
$user->upload(request()->file(), 'users');

您还可以访问一些有用的关系。

// Get a collection (array) of files that belong to the model.
$files = $user->files;

// Get a collection of image files that belong to the model.
$images = $user->files()->images()->get();

// Get a collection of video files that belong to the model.
$videos = $user->files()->videos()->get();

// You can go crazy and grab all text files created three days ago.
$files = $user->files()->where('created_at', '<=', Carbon\Carbon::now()->subDays(3))->where('type', 'like', 'text/%')->get();

轻松为用户添加个人资料图片。

// UserController.php
public function uploadProfileImage(Request $request, User $user)
{
    // Remove all previous images.
    $user->files->each(function($file) {
        $file->delete();
    });

    $user->upload(request()->file(), 'users');
}

// User.php
public function getImageAttribute()
{
    return $this->files()->images()->first()->url;
}

// Usage
<img src="{{ $user->image }}">

使用这些简单的助手检查文件是否为图片或视频。

$file->isVideo()
$file->isImage()