cloudinary-labs / cloudinary-laravel
一个 Laravel Cloudinary 包
Requires
- php: ^8.1
- ext-json: *
- cloudinary/cloudinary_php: ^2.0
- illuminate/support: ^10.0|^11.0
Requires (Dev)
- mockery/mockery: ^1.1
- orchestra/testbench: ^8.0|^9.0
- pestphp/pest: ^2.35
- sempro/phpunit-pretty-print: ^1.0
README
这是一个用于使用 Cloudinary 上传、优化、转换和交付媒体文件的 Laravel 包。此外,它提供了一个流畅且易于表达的 API,以便轻松地将媒体文件附加到 Eloquent 模型。
内容
用法
版本 8 及以下 的 Laravel 应使用 v1.x.x。
上传、检索 & 转换媒体方法调用:
上传 文件(图片、视频 或任何类型的 文件)到 Cloudinary,通过以下任何方式 检索 和 转换
/** * Using the Cloudinary Facade * Import the Facade in your Class like so: */ use CloudinaryLabs\CloudinaryLaravel\Facades\Cloudinary; use CloudinaryLabs\CloudinaryLaravel\Facades\Cloudinary; // access the admin api (https://cloudinary.com/documentation/admin_api) Cloudinary::admin(); // access the search api (https://cloudinary.com/documentation/search_api) Cloudinary::search(); // access the upload api (https://cloudinary.com/documentation/image_upload_api_reference) Cloudinary::uploadApi(); // Upload an Image File to Cloudinary with One line of Code $uploadedFileUrl = Cloudinary::upload($request->file('file')->getRealPath())->getSecurePath(); // Upload a Video File to Cloudinary with One line of Code $uploadedFileUrl = Cloudinary::uploadVideo($request->file('file')->getRealPath())->getSecurePath(); // Upload any File to Cloudinary with One line of Code $uploadedFileUrl = Cloudinary::uploadFile($request->file('file')->getRealPath())->getSecurePath(); // get url from a file $url = Cloudinary::getUrl($publicId); /** * This package also exposes a helper function you can use if you are not a fan of Facades * Shorter, expressive, fluent using the * cloudinary() function */ // access the admin api (https://cloudinary.com/documentation/admin_api) cloudinary()->admin(); // access the search api (https://cloudinary.com/documentation/search_api) cloudinary()->search(); // access the upload api (https://cloudinary.com/documentation/image_upload_api_reference) cloudinary()->uploadApi(); // Upload an image file to cloudinary with one line of code $uploadedFileUrl = cloudinary()->upload($request->file('file')->getRealPath())->getSecurePath(); // Upload a video file to cloudinary with one line of code $uploadedFileUrl = cloudinary()->uploadVideo($request->file('file')->getRealPath())->getSecurePath(); // Upload any file to cloudinary with one line of code $uploadedFileUrl = cloudinary()->uploadFile($request->file('file')->getRealPath())->getSecurePath(); // Upload an existing remote file to Cloudinary with one line of code $uploadedFileUrl = cloudinary()->uploadFile($remoteFileUrl)->getSecurePath(); // get url from a file $url = cloudinary()->getUrl($publicId); /** * You can also skip the Cloudinary Facade or helper method and laravel-ize your uploads by simply calling the * storeOnCloudinary() method on the file itself */ // Store the uploaded file on Cloudinary $result = $request->file('file')->storeOnCloudinary(); // Store the uploaded file on Cloudinary $result = $request->file->storeOnCloudinary(); // Store the uploaded file in the "lambogini" directory on Cloudinary $result = $request->file->storeOnCloudinary('lambogini'); // Store the uploaded file in the "lambogini" directory on Cloudinary with the filename "prosper" $result = $request->file->storeOnCloudinaryAs('lambogini', 'prosper'); $result->getPath(); // Get the url of the uploaded file; http $result->getSecurePath(); // Get the url of the uploaded file; https $result->getSize(); // Get the size of the uploaded file in bytes $result->getReadableSize(); // Get the size of the uploaded file in bytes, megabytes, gigabytes or terabytes. E.g 1.8 MB $result->getFileType(); // Get the type of the uploaded file $result->getFileName(); // Get the file name of the uploaded file $result->getOriginalFileName(); // Get the file name of the file before it was uploaded to Cloudinary $result->getPublicId(); // Get the public_id of the uploaded file $result->getExtension(); // Get the extension of the uploaded file $result->getWidth(); // Get the width of the uploaded file $result->getHeight(); // Get the height of the uploaded file $result->getTimeUploaded(); // Get the time the file was uploaded /** * You can also check if a file exists */ $url = Storage::disk('cloudinary')->fileExists($publicId);
将文件 附加到 Laravel Eloquent 模型
首先,将 CloudinaryLabs\CloudinaryLaravel\MediaAlly
特性导入到您的模型中,如下所示
<?php namespace App; use Illuminate\Database\Eloquent\Model; use CloudinaryLabs\CloudinaryLaravel\MediaAlly; class Page extends Model { use MediaAlly; ... }
接下来,使用以下命令发布包的迁移文件
php artisan vendor:publish --provider="CloudinaryLabs\CloudinaryLaravel\CloudinaryServiceProvider" --tag="cloudinary-laravel-migration"
注意:发布后,运行 php artisan migrate
在数据库中创建所需的表。
现在,您可以像这样将媒体资产附加到模型中
/** * How to attach a file to a Model by model creation */ $page = Page::create($this->request->input()); $page->attachMedia($file); // Example of $file is $request->file('file'); /** * How to attach a file to a Model by retrieving model records */ $page = Page::find(2); $page->attachMedia($file); // Example of $file is $request->file('file'); /** * How to retrieve files that were attached to a Model */ $filesBelongingToSecondPage = Page::find(2)->fetchAllMedia(); /** * How to retrieve the first file that was attached to a Model */ $fileBelongingToSecondPage = Page::find(2)->fetchFirstMedia(); /** * How to retrieve the last file that was attached to a Model */ $fileBelongingToSecondPage = Page::find(2)->fetchLastMedia(); /** * How to replace/update files attached to a Model */ $page = Page::find(2); $page->updateMedia($file); // Example of $file is $request->file('file'); /** * How to detach a file from a Model */ $page = Page::find(2); $page->detachMedia($file) // Example of $file is $request->file('file');
使用附加媒体方法添加转换:
/** * How to resize an image to a specific width and height, and crop it using 'fill' mode */ $options = [ 'transformation' => [ [ 'width' => 200, // Desired width 'height' => 200, // Desired height 'crop' => 'fill', // Crop mode (you can change this to 'fit' or other modes) ], ], ] $page->attachMedia($file, $options); // Example of $file is $request->file('file'); /** * How to crop an image to a specific width and height. */ $options = [ 'transformation' => [ [ 'width' => 200, // Desired width 'height' => 200, // Desired height 'crop' => 'crop', // Crop mode ], ], ] $page->attachMedia($file, $options); // Example of $file is $request->file('file'); /** * How to rotate an image by a specific degree. */ $options = [ 'transformation' => [ [ 'angle' => 45, // Rotation angle ], ], ] $page->attachMedia($file, $options); // Example of $file is $request->file('file'); /** * How to apply a filter to an image. */ $options = [ 'transformation' => [ [ 'effect' => 'grayscale', // Filter effect ], ], ] $page->attachMedia($file, $options); // Example of $file is $request->file('file'); /** * How to overlay text on an image. */ $options = [ 'transformation' => [ [ 'overlay' => [ 'font_family' => 'arial', 'font_size' => 24, 'text' => 'Hello World', ], ], ], ] $page->attachMedia($file, $options); // Example of $file is $request->file('file');
通过上传小部件上传文件:
使用此包附带 x-cld-upload-button
Blade 上传按钮组件,如下所示
<!DOCTYPE html> <html> <head> ... @cloudinaryJS </head> <body> <x-cld-upload-button> Upload Files </x-cld-upload-button> </body> </html>
您还可以使用以下其他 Blade 组件
/** * * TRANSFORMATION ACTIONS CATEGORIES: * * 1. RESIZE * - Scale * - Limit Fit * - Fill * - Fit * - Crop * - Thumbnail * - Pad * - Limit Fill * - Limit Pad * - Minimum Fit * - Minimum Pad * * * 2. ADJUST * - Improve * - Unsharp Mask * - Saturation * - Contrast * - Brightness * - Gamma * * * 3. EFFECT * - Colorize * - Blur * - Trim * - Grayscale * - Blackwhite * - Sepia * - Red Eye * - Negate * - Oil Paint * - Vignette * - Simulate Colorblind * - Pixelate * - Shadow * * * 4. DELIVERY * - Format * - Quality * - Color Space * - DPR * * 5. LAYERS * - Image Layer * - Text Layer * * */ <x-cld-image public-id="prosper" width="300" height="300"></x-cld-image> // Blade Image Component for displaying images <x-cld-video public-id="awesome"></x-cld-video> // Blade Video Component for displaying videos /** * ARTISTIC Filters * Possible values: al_dente, athena, audrey, aurora, daguerre, eucalyptus, fes, frost, hairspray, hokusai, incognito, linen, peacock, primavera, quartz, red_rock, refresh, sizzle, sonnet, ukulele, zorro * Reference: https://cloudinary.com/documentation/transformation_reference#e_art */ <x-cld-image public-id="eifrfdh65qvn8rbby3cs" crop="thumb" effect="art|sizzle" ></x-cld-image> <x-cld-image public-id="eifrfdh65qvn8rbby3cs" crop="thumb" effect="art|audrey" ></x-cld-image> <x-cld-image public-id="eifrfdh65qvn8rbby3cs" crop="thumb" effect="art|incognito" ></x-cld-image> <x-cld-image public-id="eifrfdh65qvn8rbby3cs" crop="thumb" art="incognito" ></x-cld-image> <x-cld-image public-id="eifrfdh65qvn8rbby3cs" crop="thumb" art="audrey" ></x-cld-image> /** * Colorize */ <x-cld-image public-id="couple" colorize="rgb:0000_35"></x-cld-image> /** * Blur - Applies a blurring filter to an asset. * The strength ranges from 1 to 2000 */ <x-cld-image public-id="couple" blur="599"></x-cld-image> /** * Grayscale * Converts an image to grayscale (multiple shades of gray). */ <x-cld-image public-id="couple" grayscale></x-cld-image> /** * sepia * Changes the color scheme of an image to sepia. */ <x-cld-image public-id="couple" sepia-50></x-cld-image> /** * redeye * Automatically removes red eyes in an image. */ <x-cld-image public-id="couple" redeye></x-cld-image> /** * negate * Creates a negative of an image. */ <x-cld-image public-id="couple" negate></x-cld-image> /** * oil-paint * Applies an oil painting effect. */ <x-cld-image public-id="couple" oil-paint></x-cld-image> <x-cld-image public-id="couple" oil-paint="78"></x-cld-image> /** * vignette * Applies a vignette effect to an image. * The strength level of the vignette. Range: 0 to 100 */ <x-cld-image public-id="couple" vignette></x-cld-image> <x-cld-image public-id="couple" vignette="78"></x-cld-image> /** * simulate-colorblind * Simulates the way an image would appear to someone with the specified color blind condition. * The color blind condition to simulate.Possible values: deuteranopia, protanopia, tritanopia, tritanomaly, deuteranomaly, cone_monochromacy, rod_monochromacy */ <x-cld-image public-id="couple" simulate-colorblind></x-cld-image> <x-cld-image public-id="couple" simulate-colorblind="protanopia"></x-cld-image> /** * pixelate * Applies a pixelation effect. * The width in pixels of each pixelation square. Range: 1 to 200. Default: Determined by an algorithm based on the image dimensions. */ <x-cld-image public-id="couple" pixelate></x-cld-image> <x-cld-image public-id="couple" pixelate="5"></x-cld-image> /** * shadow * Adds a gray shadow to the bottom right of an image. You can change the color and location of the shadow using the color and x,y qualifiers. * The format of the shadow is color_offsetX_offsetY_strength */ <x-cld-image public-id="couple" shadow="rgb:999_-15_-15_50"></x-cld-image> /** * unsharp-mask * Applies an unsharp mask filter to the image. * The strength of the filter. (Range: 1 to 2000, Server default: 100) */ <x-cld-image public-id="couple" unsharp-mask="1799"></x-cld-image> /** * saturation * Adjusts the color saturation. * The level of color saturation (Range: -100 to 100, Server default: 80). */ <x-cld-image public-id="couple" saturation="79"></x-cld-image> /** * brightness * Adjusts the brightness. * The level of brightness (Range: -99 to 100). */ <x-cld-image public-id="couple" brightness="80"></x-cld-image> /** * gamma * Adjusts the gamma level. * The level of gamma (Range: -50 to 150, Server default: 0). */ <x-cld-image public-id="couple" gamma="100"></x-cld-image> /** * trim * Detects and removes image edges whose color is similar to the corner pixels. * The level of tolerance for color similarity. Range: 0 to 100 * The color to trim as a named color or an RGB/A hex code. * e.g 50_yellow * 50 is for color similarity * yellow is for color override */ <x-cld-image public-id="casual_yellow_red_corners" trim="50_yellow" ></x-cld-image> /** * improve-mode * Adjusts an image's colors, contrast and brightness to improve its appearance. * Possible values: mode is 'indoor', 'outdoor' * blend is withing the range of 0 to 100. * */ <x-cld-image public-id="couple" improve-mode="indoor_99"></x-cld-image> /** * Blackwhite * Converts an image to black and white. * Threshold - The balance between black (100) and white (0). */ <x-cld-image public-id="couple" blackwhite></x-cld-image> <x-cld-image public-id="couple" blackwhite="47"></x-cld-image> /** * CARTOON Filters */ <x-cld-image public-id="eifrfdh65qvn8rbby3cs" crop="thumb" cartoonify ></x-cld-image> <x-cld-image public-id="eifrfdh65qvn8rbby3cs" crop="thumb" cartoonify="70:bw" ></x-cld-image> /** * ROTATE */ <x-cld-image public-id="eifrfdh65qvn8rbby3cs" crop="thumb" rotate="80" ></x-cld-image> /** * ROUNDED CORNERS */ <x-cld-image public-id="eifrfdh65qvn8rbby3cs" crop="thumb" rounded-corners ></x-cld-image> /** * Borders */ // Adds a solid border around an image or video. <x-cld-image public-id="eifrfdh65qvn8rbby3cs" crop="thumb" rounded-corners border="4_solid_brown" ></x-cld-image> <x-cld-image public-id="eifrfdh65qvn8rbby3cs" crop="thumb" rounded-corners border="4_solid_rgb:999" ></x-cld-image> /** * Background Color */ <x-cld-image public-id="eifrfdh65qvn8rbby3cs" crop="thumb" rotate="40" bg-color="red" rounded-corners border="4_solid_rgb:999" ></x-cld-image> /** * Face detection-based image cropping * Crop "thumb" or "crop" and gravity must be used together * Faces will target all the faces * Face will target only one face * You can specify width and height or not * You can use compass to define a fixed location within an asset to focus on e.g north_west, east, south. */ <x-cld-image public-id="couple" crop="thumb" width="150" gravity="faces" ></x-cld-image> <x-cld-image public-id="couple" crop="crop" gravity="faces"></x-cld-image> <x-cld-image public-id="couple" crop="crop" gravity="face"></x-cld-image> <x-cld-image public-id="couple" crop="crop" width="200" height="200" gravity="compass:east" ></x-cld-image> <x-cld-image public-id="couple" crop="crop" width="200" height="200" gravity="microwave" ></x-cld-image>
通过命令行进行媒体管理:
/** * Back-up Files on Cloudinary */ php artisan cloudinary:backup /** * Delete a File on Cloudinary */ php artisan cloudinary:delete /** * Fetch a File from Cloudinary */ php artisan cloudinary:fetch /** * Rename a File from Cloudinary */ php artisan cloudinary:rename /** * Upload a File to Cloudinary */ php artisan cloudinary:upload
安装
要获取 Laravel Cloudinary 的最新版本,只需要求它
composer require cloudinary-labs/cloudinary-laravel
或者将以下行添加到 composer.json
文件的 require 块中。
使用 Laravel 9 的应用程序
"cloudinary-labs/cloudinary-laravel": "2.0.0"
使用 Laravel 8 及以下版本的应用程序
"cloudinary-labs/cloudinary-laravel": "1.0.4"
然后,您需要运行 composer install
或 composer update
下载它并更新自动加载器。
安装 Laravel Cloudinary 后,您需要注册服务提供者。打开 config/app.php
并将以下内容添加到 providers
键中。
'providers' => [ ... CloudinaryLabs\CloudinaryLaravel\CloudinaryServiceProvider::class, ... ]
注意:如果您使用 Laravel >= 5.5,您可以跳过此步骤(将上面的代码添加到 providers 键中)并转到
配置
同时,按照如下方式注册 Cloudinary Facade
'aliases' => [ ... 'Cloudinary' => CloudinaryLabs\CloudinaryLaravel\Facades\Cloudinary::class, ... ]
注意:如果您使用 Laravel >= 9.0,您可以跳过注册 facades 的步骤(将上面的代码添加到注册 facades 的步骤中)并可以在需要它的任何类中导入它,如下所示
... use CloudinaryLabs\CloudinaryLaravel\Facades\Cloudinary; ...
配置
您可以使用以下命令发布配置文件
php artisan vendor:publish --provider="CloudinaryLabs\CloudinaryLaravel\CloudinaryServiceProvider" --tag="cloudinary-laravel-config"
一个名为 cloudinary.php
的配置文件,其中包含一些合理的默认值,将被放置在您的 config
目录中
<?php return [ /* |-------------------------------------------------------------------------- | Cloudinary Configuration |-------------------------------------------------------------------------- | | An HTTP or HTTPS URL to notify your application (a webhook) when the process of uploads, deletes, and any API | that accepts notification_url has completed. | | */ 'notification_url' => env('CLOUDINARY_NOTIFICATION_URL'), /* |-------------------------------------------------------------------------- | Cloudinary Configuration |-------------------------------------------------------------------------- | | Here you may configure your Cloudinary settings. Cloudinary is a cloud hosted | media management service for all file uploads, storage, delivery and transformation needs. | | */ 'cloud_url' => env('CLOUDINARY_URL'), /** * Upload Preset From Cloudinary Dashboard * */ 'upload_preset' => env('CLOUDINARY_UPLOAD_PRESET'), /** * Route to get cloud_image_url from Blade Upload Widget */ 'upload_route' => env('CLOUDINARY_UPLOAD_ROUTE'), /** * Controller action to get cloud_image_url from Blade Upload Widget */ 'upload_action' => env('CLOUDINARY_UPLOAD_ACTION'), ];
API 密钥
打开您的 .env
文件并添加您的 API 环境变量,upload_preset(这是可选的,直到您需要使用小部件)如下所示
CLOUDINARY_URL=xxxxxxxxxxxxx CLOUDINARY_UPLOAD_PRESET=xxxxxxxxxxxxx CLOUDINARY_NOTIFICATION_URL=
注意:您需要从您的 Cloudinary 仪表板 获取这些凭据。CLOUDINARY_URL 是您 Cloudinary 仪表板中显示的 API 环境变量。使用那里的复制按钮以获取完整的 URL
如果您使用类似 heroku、forge、digital ocean 等托管服务,请确保将上述详细信息添加到您的配置变量中。
Cloudinary JS
Cloudinary 使用自家的 JavaScript 库来启动 Cloudinary 上传小部件。您可以通过在应用程序布局的结束标签之前放置 @cloudinaryJS 指令来加载 JavaScript 库。
<head> ... @cloudinaryJS </head>
注意:只有在您决定使用上传小部件的情况下才加载此库。如果您正在使用此包作为 LARAVEL API 后端,则无需执行此操作!*
免责声明
Cloudinary Labs 下提供的此软件/代码是一个不受支持的预生产原型,正在进一步开发中,并按“原样”提供,不提供任何类型的保证,无论是明示的还是暗示的,包括但不限于,关于适销性和适用于特定目的的暗示保证被排除。此外,Cloudinary 没有义务提供软件的商业版本。
您使用软件/代码的风险由您自行承担,Cloudinary 不会对任何直接、间接、偶然、特殊、示范性、后果性或类似的损害(包括但不限于,替代商品或服务的采购;使用、数据或利润的损失;或业务中断)负责,无论损害是如何造成的,以及根据任何理论的责任,无论是合同、严格责任还是侵权(包括疏忽或其他)。
请勿上传任何机密或个人身份信息到软件中。软件的所有权和使用权始终属于 Cloudinary 或由 Cloudinary 授权。
贡献
我们欢迎通过 PR 的社区贡献,并将全部归功于贡献者。有关详细信息,请参阅 contributing.md。
许可证
MIT 许可证(MIT)。请参阅 许可文件 获取更多信息。