当前位置: 首页 > 软件库 > 开发工具 > PHP开发工具 >

laravel-imageup

授权协议 MIT License
开发语言 PHP
所属分类 开发工具、 PHP开发工具
软件类型 开源软件
地区 不详
投 递 者 景哲
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

Laravel ImageUp

Latest Version on PackagistSoftware LicenseBuild StatusTotal Downloads

The qcod/laravel-imageup is a trait which gives you auto upload, resize and crop for image feature with tons of customization.

Installation

You can install the package via composer:

$ composer require qcod/laravel-imageup

The package will automatically register itself. In case you need to manually register it you can by adding it in config/app.php providers array:

QCod\ImageUp\ImageUpServiceProvider::class

You can optionally publish the config file with:

php artisan vendor:publish --provider="QCod\ImageUp\ImageUpServiceProvider" --tag="config"

It will create config/imageup.php with all the settings.

Getting Started

To use this trait you just need to add use HasImageUploads on the Eloquent model and define all the fields which needs to store the images in database.

Model

<?php
namespace App;

use QCod\ImageUp\HasImageUploads;
use Illuminate\Database\Eloquent\Model;

class User extends Model {
    use HasImageUploads;
    
    // assuming `users` table has 'cover', 'avatar' columns
    // mark all the columns as image fields 
    protected static $imageFields = [
        'cover', 'avatar'
    ];
}

Once you marked all the image fields in model it will auto upload the image whenever you save the model by hooking in Model::saved() event.It will also update the database with new stored file path and if finds old image it will be deleted once new image is uploaded.

Image field should be as as VARCHAR in database table to store the path of uploaded image.

In Controller

<?php
namespace App;
use App\Http\Controllers\Controller;

class UserController extends Controller {
    public function store(Request $request){
        return User::create($request->all());
    }
}

Make sure to run php artisan storage:link to see the images from public storage disk

That's it, with above setup when ever you hit store method with post request and if cover or avatar named file is present on request() it will be auto uploaded.

Upload Field options

ImageUp gives you tons of customization on how the upload and resize will be handled from defined field options, following are the things you can customize:

<?php
namespace App;

use QCod\ImageUp\HasImageUploads;
use Illuminate\Database\Eloquent\Model;

class User extends Model {
    
    use HasImageUploads;
    
    // which disk to use for upload, can be override by field options 
    protected $imagesUploadDisk = 'local';
    
    // path in disk to use for upload, can be override by field options 
    protected $imagesUploadPath = 'uploads';
    
    // auto upload allowed 
    protected $autoUploadImages = true;
    
    // all the images fields for model
    protected static $imageFields = [
        'avatar' => [
            // width to resize image after upload
            'width' => 200,
            
            // height to resize image after upload
            'height' => 100,
            
            // set true to crop image with the given width/height and you can also pass arr [x,y] coordinate for crop.
            'crop' => true,
            
            // what disk you want to upload, default config('imageup.upload_disk')
            'disk' => 'public',
            
            // a folder path on the above disk, default config('imageup.upload_directory')
            'path' => 'avatars',
            
            // placeholder image if image field is empty
            'placeholder' => '/images/avatar-placeholder.svg',
            
            // validation rules when uploading image
            'rules' => 'image|max:2000',
            
            // override global auto upload setting coming from config('imageup.auto_upload_images')
            'auto_upload' => false,
            
            // if request file is don't have same name, default will be the field name
            'file_input' => 'photo',
            
            // a hook that is triggered before the image is saved
            'before_save' => BlurFilter::class,
            
            // a hook that is triggered after the image is saved
            'after_save' => CreateWatermarkImage::class
        ],
        'cover' => [
            //...    
        ]
    ];
    
    // any other than image file type for upload
    protected static $fileFields = [
            'resume' => [
                // what disk you want to upload, default config('imageup.upload_disk')
                'disk' => 'public',
                
                // a folder path on the above disk, default config('imageup.upload_directory')
                'path' => 'docs',
                
                // validation rules when uploading file
                'rules' => 'mimes:doc,pdf,docx|max:1000',
                
                // override global auto upload setting coming from config('imageup.auto_upload_images')
                'auto_upload' => false,
                
                // if request file is don't have same name, default will be the field name
                'file_input' => 'cv',
                
                // a hook that is triggered before the file is saved
                'before_save' => HookForBeforeSave::class,
                
                // a hook that is triggered after the file is saved
                'after_save' => HookForAfterSave::class
            ],
            'cover_letter' => [
                //...    
            ]
        ];
}

Customize filename

In some case you will need to customize the saved filename. By default it will be $file->hashName() generated hash.

You can do it by adding a method on the model with {fieldName}UploadFilePath naming convention:

class User extends Model {
    use HasImageUploads;
    
    // assuming `users` table has 'cover', 'avatar' columns
    // mark all the columns as image fields 
    protected static $imageFields = [
        'cover', 'avatar'
    ];
    
    // override cover file name
    protected function coverUploadFilePath($file) {
        return $this->id . '-cover-image.jpg';
    }
}

Above will always save uploaded cover image as uploads/1-cover-image.jpg.

Make sure to return only relative path from override method.

Request file will be passed as $file param in this method, so you can get the extension or original file name etc to build the filename.

// override cover file name
    protected function coverUploadFilePath($file) {
        return $this->id .'-'. $file->getClientOriginalName();
    }
    
    /** Some of methods on file */
    // $file->getClientOriginalExtension()
    // $file->getRealPath()
    // $file->getSize()
    // $file->getMimeType()

Available methods

You are not limited to use auto upload image feature only. This trait will give you following methods which you can use to manually upload and resize image.

Note: Make sure you have disabled auto upload by setting protected $autoUploadImages = false;on model or dynamiclly by calling $model->disableAutoUpload(). You can also disable it for specifig field by calling $model->setImagesField(['cover' => ['auto_upload' => false]);otherwise you will be not seeing your manual uploads, since it will be overwritten by auto upload upon model save.

$model->uploadImage($imageFile, $field = null) / $model->uploadFile($docFile, $field = null)

Upload image/file for given $field, if $field is null it will upload to first image/file option defined in array.

$user = User::findOrFail($id);
$user->uploadImage(request()->file('cover'), 'cover');
$user->uploadFile(request()->file('resume'), 'resume');

$model->setImagesField($fieldsOptions) / $model->setFilesField($fieldsOptions)

You can also set the image/file fields dynamically by calling $model->setImagesField($fieldsOptions) / $model->setFilesField($fieldsOptions) with field options, it will replace fields defined on model property.

$user = User::findOrFail($id);

$fieldOptions = [
    'cover' => [ 'width' => 1000 ],
    'avatar' => [ 'width' => 120, 'crop' => true ],    
];

// override image fields defined on  model 
$user->setImagesField($fieldOptions);

$fileFieldOption = [
    'resume' => ['path' => 'resumes']
];

// override file fields defined on  model
$user->setFilesField($fileFieldOption);

$model->hasImageField($field) / $model->hasFileField($field)

To check if field is defined as image/file field.

$model->deleteImage($filePath) / $model->deleteFile($filePath)

Delete any image/file if it exists.

$model->resizeImage($imageFile, $fieldOptions)

If you have image already you can call this method to resize it with the same options we have used for image fields.

$user = User::findOrFail($id);

// resize image, it will give you resized image, you need to save it  
$imageFile = '/images/some-big-image.jpg';
$image = $user->resizeImage($imageFile, [ 'width' => 120, 'crop' => true ]);

// or you can use uploaded file
$imageFile = request()->file('avatar');
$image = $user->resizeImage($imageFile, [ 'width' => 120, 'crop' => true ]);

$model->cropTo($x, $y)->resizeImage($imageFile, $field = null)

You can use this cropTo() method to set the x and y coordinates of cropping. It will be very useful if you are getting coordinate from some sort of font-end image cropping library.

$user = User::findOrFail($id);

// uploaded file from request
$imageFile = request()->file('avatar');

// coordinates from request
$coords = request()->only(['crop_x', 'crop_y']);

// resizing will give you intervention image back
$image = $user->cropTo($coords)
    ->resizeImage($imageFile, [ 'width' => 120, 'crop' => true ]);

// or you can do upload and resize like this, it will override field options crop setting
$user->cropTo($coords)
    ->uploadImage(request()->file('cover'), 'avatar');

$model->imageUrl($field) / $model->fileUrl($field)

Gives uploaded file url for given image/file field.

$user = User::findOrFail($id);

// in your view 
<img src="{{ $user->imageUrl('cover') }}" alt="" />
// http://www.example.com/storage/uploads/iGqUEbCPTv7EuqkndE34CNitlJbFhuxEWmgN9JIh.jpeg

$model->imageTag($field, $attribute = '')

It gives you <img /> tag for a field.

{!! $model->imageTag('avatar') !!}
<!-- <img src="http://www.example.com/storage/uploads/iGqUEbCPTv7EuqkndE34CNitlJbFhuxEWmgN9JIh.jpeg" /> -->

{!! $model->imageTag('avatar', 'class="float-left mr-3"') !!}
<!-- <img src="http://www.example.com/storage/uploads/iGqUEbCPTv7EuqkndE34CNitlJbFhuxEWmgN9JIh.jpeg" class="float-left mr-3 /> -->

Hooks

Hooks allow you to apply different type of customizations or any other logic that you want to take place before or after the image is saved.

Definition types

You can define hooks by specifying a class name

protected static $imageFields = [
    'avatar' => [
        'before_save' => BlurFilter::class,
    ],
    'cover' => [
        //...    
    ]
];

The hook class must have a method named handle that will be called when the hook is triggered.An instance of the intervention image will be passed to the handle method.

class BlurFilter {
    public function handle($image) {
        $image->blur(10);
    }
}

The class based hooks are resolved through laravel ioc container, which allows you to inject any dependencies through the constructor.

Keep in mind you will be getting resized image in before and after save hook handler if you have defined field option with width or height.Sure you can get original image from request()->file('avatar') any time you want.

The second type off hook definition is callback hooks.

$user->setImagesField([
    'avatar' => [
        'before_save' => function($image) {
            $image->blur(10);
        },
    ],
    'cover' => [
        //...    
    ]
]);

The callback will receive the intervention image instance argument as well.

Hook types

There are two types of hooks a before_save and after_save hooks.

The before_save hook is called just before the image is saved to the disk.Any changes made to the intervention image instance within the hook will be applied to the output image.

$user->setImagesField([
    'avatar' => [
        'width' => 100,
        'height' => 100,
        'before_save' => function($image) {
            // The image will be 50 * 50, this will override the 100 * 100 
            $image->resize(50, 50);
        },
    ]
]);

The after_save hook is called right after the image was saved to the disk.

$user->setImagesField([
    'logo' => [
        'after_save' => function($image) {
            // Create a watermark image and save it
        },
    ]
]);

Config file

<?php

return [

    /**
     * Default upload storage disk
     */
    'upload_disk' => 'public',

    /**
     * Default Image upload directory on the disc
     * eg. 'uploads' or 'user/avatar'
     */
    'upload_directory' => 'uploads',

    /**
     * Auto upload images from incoming Request if same named field or
     * file_input field on option present upon model update and create.
     * can be override in individual field options
     */
    'auto_upload_images' => true,

    /**
     * It will auto delete images once record is deleted from database
     */
    'auto_delete_images' => true,

    /**
     * Set an image quality
     */
    'resize_image_quality' => 80
];

Changelog

Please see CHANGELOG for more information on what has changed recently.

Testing

The package contains some integration/smoke tests, set up with Orchestra. The tests can be run via phpunit.

$ composer test

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email saquibweb@gmail.com instead of using the issue tracker.

Credits

About QCode.in

QCode.in (https://www.qcode.in) is blog by Saqueib which covers All about Full Stack Web Development.

License

The MIT License (MIT). Please see License File for more information.

  • Laravel ImageUp qcod/laravel-imageup 是一个可让您通过大量自定义功能自动上传,调整图像大小和裁剪图像功能。 安装 您可以通过composer安装该软件包: $ composer require qcod/laravel-imageup 软件包将自动注册。如果需要手动注册,可以通过将其添加到config/app.phpproviders数组中来进行注册: QCo

  • 小伙伴说MD编辑器不好用,因为复制粘贴不方便。。。。所以我换了一个编辑器整合,选择了老朋友wangEditor,下面为大家介绍怎么在laravel v6.9 + laravel-admin v1.7 + wangEditor2的情况下上传图片 第一步: composer require jxlwqq/wang-editor2 第二步:发布配置文件: php artisan vendor:publ

  • 迁移文件 <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateConfigTable extends Migration { /** * R

  • 在我们使用 laravel-admin 作为系统管理后台的时候经常会用到 editor 作为编辑器来给我们编辑内容,但是在 laravel-admin 的官网上只介绍了怎么下载使用,其中有一个问题就是上传图片的问题,我们需要开发一个上传图片的接口。 基本的下载安装去看 laravel-admin 官网,下面我来贴一下代码 先来新建一个 ImageUploadHandler.php 来作为处理传入的

  • 直播源码开发,laravel-admin整合wangEditor2及上传图片 第一步: composer require jxlwqq/wang-editor2 第二步:发布配置文件: php artisan vendor:publish --tag=laravel-admin-wang-editor2 第三步:修改laravel-admin配置文件config/admin.php中的exte

  • laravel-admin后台自带的地图有腾讯地图和谷歌地图 1.  1.1 创建项目 composer create-project laravel/laravel=5.5 blog_wangeditor --prefer-dist 1.2 创建数据库及配置文件 vim .env 1.3 安装中文包 composer require "caouecs/laravel-lang:~3.0" 安装之

  • config/filesystems.php中找到’disks’ 'disks' => [ 'local' => [ 'driver' => 'local', 'root' => public_path('uploads'), ], //你的预配置 'goods'=>[

 相关资料
  • Laravel 是一套简洁、优雅的PHP Web开发框架(PHP Web Framework)。它可以让你从面条一样杂乱的代码中解脱出来;它可以帮你构建一个完美的网络APP,而且每行代码都可以简洁、富于表达力。 功能特点 1、语法更富有表现力 你知道下面这行代码里 “true” 代表什么意思么? $uri = Uri::create(‘some/uri’, array(), array(), tr

  • 我需要空间/Laravel权限的帮助。当我试图分配它给我错误哎呀,看起来像出了问题。 错误 Connection.php第761行中的QueryExcema:SQLSTATE[23000]:完整性约束冲突:1048列role_id不能为空(SQL:插入到(,)值(9,))

  • Laravel 作为现在最流行的 PHP 框架,其中的知识较多,所以单独拿出来写一篇。 简述 Laravel 的生命周期 Laravel 采用了单一入口模式,应用的所有请求入口都是 public/index.php 文件。 注册类文件自动加载器 : Laravel通过 composer 进行依赖管理,无需开发者手动导入各种类文件,而由自动加载器自行导入。 创建服务容器:从 bootstrap/ap

  • 简介 Laravel Scout 为 Eloquent 模型 全文搜索提供了简单的,基于驱动的解决方案。通过使用模型观察者,Scout 会自动同步 Eloquent 记录的搜索索引。 目前,Scout 自带一个 Algolia 驱动;不过,编写自定义驱动很简单, 你可以轻松的通过自己的搜索实现来扩展 Scout。 安装 首先,通过 Composer 包管理器来安装 Scout: composer

  • 简介 Laravel 致力于让整个 PHP 开发体验变得愉快, 包括你的本地开发环境。 Vagrant 提供了一种简单,优雅的方式来管理和配置虚拟机。 Laravel Homestead 是一个官方预封装的 Vagrant box,它为你提供了一个完美的开发环境,而无需在本地机器安装 PHP 、Web 服务器和其他服务器软件。不用担心会搞乱你的操作系统!Vagrant boxes 是一次性的。如果

  • WebStack-Laravel 一个开源的网址导航网站项目,具备完整的前后台,您可以拿来制作自己的网址导航。 部署 克隆代码: git clone https://github.com/hui-ho/WebStack-Laravel.git 安装依赖: composer installphp artisan key:generate 编辑配置: cp .env.example .env ...D