levoolabs/imageable

Eloquent Image模型,用于使用intervention/imagecache上传和显示图片

1.1.2 2019-01-16 22:43 UTC

This package is not auto-updated.

Last update: 2024-09-20 03:28:18 UTC


README

LevooLabs Imageable是一个易于使用的Eloquent Image模型,用于通过intervention/imagecache上传和显示图片。该软件包包括用于在Image模型和任何其他Eloquent模型之间添加简单连接的属性。

演示

获取模型图片的多种大小

$topic = Topic::where('name', 'Awsome topic')->first();
echo $topic->image->s; // Small image url
echo $topic->image->m; // Medium image url
echo $topic->image->l; // Large image url
echo $topic->image->o; // Original image url

获取辅助图片

foreach ($product->secondary_images as $image) {
    echo $image->s;
}

检查模型是否已上传图片

if ($topic->has_image) {
    //
}

将图片上传到服务器

public function uploadImageAjax(Request $request, Topic $topic)
{
    if ($request->ajax()) {
        $image = $topic->store_image($request->file('file'));
        return response()->json(['ok' => $image->id], 200);
    }
    abort(404);
}

或使用store_images($files, $image_type = null)上传多个图片。

从服务器删除图片

$topic->delete_image();

或使用delete_images()删除与模型关联的所有图片。

安装

步骤 1: 安装包

通过Composer安装包。

在终端中运行Composer require命令

composer require levoolabs/imageable

步骤 2: 迁移

使用Artisan命令运行迁移

php aritsan migrate

这将创建以下表

Schema::create('images', function(Blueprint $table) {
    $table->increments('id');
    $table->integer('imageable_id')->unsigned();
    $table->string('imageable_type');
    $table->string('image_type');
    $table->string('image_path'); #NOTE relative filename with extension -> /folder/folder/filename.ext
    $table->timestamps();
});

步骤 3: 发布资源

使用以下命令发布intervention配置文件和Imageable默认图片

php artisan vendor:publish

步骤 4.1: 属性

对于最简单的使用,只需将SingleImageableTraitMultiImageableTrait包含到您的Eloquent模型中,然后您就设置好了。

class Topic extends Model
{
    use \LevooLabs\Imageable\Traits\SingleImageableTrait;
    
    protected $table = 'topics';
    
    protected $fillable = [
        'title'
    ];
    
}

或者,您可以通过设置以下属性来增加灵活性

class Product extends Model
{
    use \LevooLabs\Imageable\Traits\MultiImageableTrait;

    public $template_base_name = "product";
    
    protected $image_type = MyConstants\ImageType::PRODUCT_MAIN;
    protected $secondary_image_type = MyConstants\ImageType::PRODUCT;

    protected $default_image_name = "product.jpg";
    
    protected $extension = "jpg";

    /* ... */
}
  • $template_base_name包含在imagecache配置文件中定义的滤镜的基准名称。
  • $image_type$secondary_image_type属性持有images表中image_type列的值。在MultiImageableTrait中仅使用$secondary_image_type
  • $default_image_name是位于public/images/imageable文件夹中的占位符图片文件的名称,用于没有上传图片的模型。

步骤 4.2: 自定义滤镜(可选)

如果您在模型中设置了$template_base_name值,您必须在config/imagecache.php文件中定义该模板的滤镜。

    'product'   => \App\ImageFilters\Product\Upload::class,
    'product-s' => \App\ImageFilters\Product\Small::class,
    'product-m' => \App\ImageFilters\Product\Medium::class,
    'product-l' => \App\ImageFilters\Product\Large::class,

您可以在此处了解有关Intervention Image Filters的更多信息这里

许可证

LevooLabs Imageable在MIT许可证下发布。

版权 2018 LevooLabs