亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄
Installation and Setup
Adding and Managing Media
Generating Conversions and Thumbnails
Advanced Features: Custom Disks, URLs, and Cleanup
首頁 php框架 Laravel 如何使用 Spatie Laravel Medialibrary 包管理媒體文件?

如何使用 Spatie Laravel Medialibrary 包管理媒體文件?

Oct 13, 2025 am 05:18 AM

Spatie Laravel Medialibrary 簡化了Laravel 中的媒體文件管理,通過安裝包、發(fā)布遷移和配置、使用InteractsWithMedia trait 實現(xiàn)模型關聯(lián),支持文件上傳、多集合分類、自定義存儲磁盤、生成縮略圖轉(zhuǎn)換及清理機制,提供簡潔API 和強大功能。

How to manage media files with the Spatie Laravel Medialibrary package?

Managing media files in Laravel just got simpler with the Spatie Laravel Medialibrary package. It lets you attach multiple files to Eloquent models, handle conversions (like thumbnails), organize files, and manage disk storage with minimal code. Here's how to set it up and use it effectively.

Installation and Setup

To get started, install the package via Composer:

  • composer require spatie/laravel-medialibrary

Publish and run the migration to create the media table:

  • php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider" --tag="migrations"
  • php artisan migrate

Publish the config file if you need customization:

  • php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider" --tag="config"

Add the InteractsWithMedia trait to your Eloquent model:

 use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

class Product extends Model implements HasMedia
{
    use InteractsWithMedia;
}

Adding and Managing Media

You can attach files to a model instance using the addMedia method:

 $product = Product::find(1);
$product
    ->addMedia($request->file('image'))
    ->toMediaCollection('images');

This stores the file on the default disk and saves metadata in the media table. You can define named collections like images , documents , etc., for better organization.

To retrieve media:

 $media = $product->getMedia('images');
foreach ($media as $item) {
    echo $item->getUrl(); // Full URL to the file
}

Delete media when needed:

 $product->getFirstMedia('images')->delete();

Generating Conversions and Thumbnails

The package supports automatic image conversions. Define them in your model:

 public function registerMediaConversions(Media $media = null): void
{
    $this->addMediaConversion('thumb')
         ->width(100)
         ->height(100);

    $this->addMediaConversion('preview')
         ->width(500)
         ->height(300)
         ->nonQueued();
}

Now, when an image is added, both thumb and preview versions are generated. Use them like this:

 <img  src="{{ $product- alt="如何使用 Spatie Laravel Medialibrary 包管理媒體文件?" >getFirstMediaUrl(&#39;images&#39;, &#39;thumb&#39;) }}">

Conversions are queued by default unless marked with nonQueued() .

Advanced Features: Custom Disks, URLs, and Cleanup

You can store media on different disks (eg, S3, public, local). Set the disk per collection:

 ->toMediaCollection(&#39;documents&#39;, &#39;s3&#39;);

Customize URLs or path generators by creating a custom path generator class. For example, organize files by model type and ID.

Enable responsive images or extract metadata (EXIF) using optional addons like spatie/laravel-medialibrary-pro or additional configurations.

Cleanup old or unused media with:

  • php artisan medialibrary:regenerate – Re-create conversions
  • Model events automatically clean up media when a model is deleted (if using deleting event cleanup)

Basically, Spatie's Medialibrary streamlines file handling in Laravel apps—clean API, solid features, and great documentation make it a go-to for managing uploads.

以上是如何使用 Spatie Laravel Medialibrary 包管理媒體文件?的詳細內(nèi)容。更多資訊請關注PHP中文網(wǎng)其他相關文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發(fā)現(xiàn)涉嫌抄襲或侵權的內(nèi)容,請聯(lián)絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動的應用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT

Stock Market GPT

人工智慧支援投資研究,做出更明智的決策

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

如何將消息記錄到Laravel中的文件? 如何將消息記錄到Laravel中的文件? Sep 21, 2025 am 06:04 AM

LaraveluseMonologTologMessagesViathelogFacade,withDefaultLogSstoreDinstorage/logs/logaver.log.configurechannelsinconfig/loggpocontrolOlOutput; theDefeftoconTrolOutput; theDefeftStackChannAnneLagateSmultipleHersMultipleHerslikeSlikeSlikesingLikeSingLikeSingle,whatwrile.afile.usel.uselel.uselel.usecy.useleleel.use)

如何在Laravel中驗證API 如何在Laravel中驗證API Sep 18, 2025 am 12:26 AM

installlaravelsanctumviaCompoSerandPublishItsFiles,thenRunMigrations.2.AddthehasapitokenStraittheUserModel.3.definelogin,logout of lokout of anduserroutesinapi.php

如何使用Laravel的Hasmanythrough關係? 如何使用Laravel的Hasmanythrough關係? Sep 17, 2025 am 06:38 AM

AcountrycanaccessallpostSthrouserSerssinghasmanyThrough

如何使用Laravel中的路線資源控制器? 如何使用Laravel中的路線資源控制器? Sep 24, 2025 am 05:05 AM

Laravel資源控制器通過RESTful路由快速處理CRUD操作,使用Artisan命令生成控制器並註冊資源路由,單行代碼即可創(chuàng)建全部標準路由,支持限制動作、添加中間件及命名,結(jié)合路由模型綁定可自動解析參數(shù),提升開發(fā)效率並保持代碼結(jié)構清晰。

如何使用Laravel Sanctum實施API身份驗證? 如何使用Laravel Sanctum實施API身份驗證? Sep 19, 2025 am 04:08 AM

toimplementApiAthenticationWithlaravelsanctum,YouneEdtoStepoken的authenticationthatallowsspas,mobileApps,andth-thired-thired-partyservicestoseStoseStoSecerlelyAccessyourapi.sanctumprovidesleightigeslightightightwerightightweightightweightightappablebybybybybybyissugyapitokensthatcanthatcan

如何在Laravel控制器中重定向用戶? 如何在Laravel控制器中重定向用戶? Sep 21, 2025 am 05:26 AM

使用redirect()輔助函數(shù)可實現(xiàn)Laravel控制器中的重定向,如redirect()->route('home')跳轉(zhuǎn)到命名路由,redirect('/dashboard')跳轉(zhuǎn)到指定URL,redirect()->back()返回上一頁,結(jié)合withInput()保留表單數(shù)據(jù),with()傳遞會話消息,推薦使用命名路由以提高可維護性。

如何在Laravel編寫RAW SQL查詢? 如何在Laravel編寫RAW SQL查詢? Sep 24, 2025 am 02:55 AM

使用DB門面執(zhí)行原生SQL,根據(jù)查詢類型選擇DB::select、DB::insert、DB::update或DB::delete,並用參數(shù)綁定防止SQL注入;結(jié)構變更可用DB::unprepared;結(jié)合DB::raw可在查詢構造器中嵌入原生表達式。

如何連接到Laravel的第二個數(shù)據(jù)庫? 如何連接到Laravel的第二個數(shù)據(jù)庫? Sep 17, 2025 am 01:42 AM

配置第二個數(shù)據(jù)庫連接:在config/database.php中添加新連接並設置.env變量;2.使用DB::connection('mysql_second')或模型$connection屬性指定連接;3.運行時可用on()方法動態(tài)切換;4.遷移時用Schema::connection()並配合--database選項執(zhí)行。

See all articles