### Installing Sphinx Documentation Tool (Bash) Source: https://github.com/plank/laravel-mediable/blob/master/CONTRIBUTING.md This command uses pip, the Python package installer, to install the Sphinx documentation generator. Sphinx is required to build the project's documentation from its source files. Ensure Python and pip are installed and accessible in your environment. ```Bash $ pip install Sphinx ``` -------------------------------- ### Running PHPUnit Tests (Bash) Source: https://github.com/plank/laravel-mediable/blob/master/CONTRIBUTING.md This snippet shows the command to execute the project's unit tests using PHPUnit. It runs the configured test suite to check for regressions and verify new functionality. Requires PHPUnit to be installed and the project's test setup to be complete. ```Bash $ phpunit ``` -------------------------------- ### Install Package via Composer Bash Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/installation.rst Installs the `plank/laravel-mediable` package into your Laravel project using the Composer dependency manager. This command downloads the package and its dependencies. ```bash $ composer require plank/laravel-mediable ``` -------------------------------- ### Run Database Migrations via Artisan Bash Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/installation.rst Executes the package's database migration file using Artisan to create the necessary tables for storing media information and relationships. This step is required after publishing the migrations. ```bash $ php artisan migrate ``` -------------------------------- ### Attach Media Record to Eloquent Model PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/installation.rst Attaches a previously uploaded `Media` model instance to an Eloquent model using the `attachMedia` method provided by the `Mediable` trait. The media is attached with a specific tag ('thumbnail' in this example) for easy retrieval. ```php attachMedia($media, 'thumbnail'); ``` -------------------------------- ### Retrieve and Display Attached Media PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/installation.rst Retrieves attached media records for an Eloquent model using the `withMedia` scope and the `getMedia` method, filtering by the tag. It then gets the URL of the first attached media item with that tag. ```php find($postId); echo $post->getMedia('thumbnail')->first()->getUrl(); ``` -------------------------------- ### Building Sphinx Documentation to HTML (Bash) Source: https://github.com/plank/laravel-mediable/blob/master/CONTRIBUTING.md These commands first change the current directory to the `docs/` subdirectory, then execute the `make html` command. This triggers Sphinx (which is configured via the Makefile in `docs/`) to build the documentation in HTML format. Requires Sphinx and `make` to be installed and the documentation sources to be present. ```Bash $ cd docs/\n$ make html ``` -------------------------------- ### Register MediaUploader Facade in Laravel PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/installation.rst Optionally registers the `MediaUploader` facade alias in the `config/app.php` file's `aliases` array. This allows using the `MediaUploader` facade for convenience when uploading files. ```php 'aliases' => [ //... 'MediaUploader' => Plank\Mediable\Facades\MediaUploader::class, //... ] ``` -------------------------------- ### Publish Configuration and Migrations via Artisan Bash Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/installation.rst Publishes the package's configuration file (`config/mediable.php`) and migration file to your application using the Artisan command-line tool. This allows you to customize the package settings and run the required database migrations. ```bash $ php artisan vendor:publish --provider="Plank\Mediable\MediableServiceProvider" ``` -------------------------------- ### Configuring Laravel Filesystem Disks - PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/configuration.rst Defines storage locations for files using Laravel's built-in filesystem component. Shows examples for local storage paths, specifying the driver, root directory, base URL for public access, and visibility. ```php [ 'local' => [ 'driver' => 'local', 'root' => storage_path('app'), 'url' => 'https://example.com/storage/app', 'visibility' => 'public' ], 'uploads' => [ 'driver' => 'local', 'root' => public_path('uploads'), 'url' => 'https://example.com/uploads', 'visibility' => 'public' ], ] //... ``` -------------------------------- ### Upload File using MediaUploader Facade PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/installation.rst Uses the `MediaUploader` facade to upload a file from a source (like a request file) to a specified destination disk and directory. The method returns a `Media` model instance representing the uploaded file. ```php file('thumbnail')) ->toDestination('s3', 'posts/thumbnails') ->upload(); ``` -------------------------------- ### Register Service Provider in Laravel PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/installation.rst Manually registers the package's service provider in the `config/app.php` file's `providers` array. This step is typically not needed in Laravel 5.5+ with auto-discovery enabled. ```php 'providers' => [ //... Plank\Mediable\MediableServiceProvider::class, //... ]; ``` -------------------------------- ### Defining Custom Mediable Aggregate Types - PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/configuration.rst Allows the definition of custom aggregate types to group files with different MIME types and extensions under a single category. This makes querying for similar media easier, as shown with the 'markup' example. ```php [ //... 'markup' => [ 'mime_types' => [ 'text/markdown', 'text/html', 'text/xml', 'application/xml', 'application/xhtml+xml', ], 'extensions' => [ 'md', 'html', 'htm', 'xhtml', 'xml' ] ], //... ] //... ``` -------------------------------- ### Add Mediable Trait and Interface to Eloquent Model PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/installation.rst Adds the `Mediable` trait and implements the `MediableInterface` to an Eloquent model (e.g., `Post`). This provides the model with methods for attaching, detaching, and retrieving media. ```php 'prefixed_mediables', ``` -------------------------------- ### Streaming Private Media File Download PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/media.rst Provides an example of how to stream a private media file directly from the server using a Laravel response, allowing authorized users to download files without exposing a public URL. ```php streamDownload( function() use ($media) { $stream = $media->stream(); while($bytes = $stream->read(1024)) { echo $bytes; } }, $media->basename, [ 'Content-Type' => $media->mime_type, 'Content-Length' => $media->size ] ); ``` -------------------------------- ### Navigating Media Variant Family (Laravel Mediable, PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Shows methods for traversing between different media records within the same variant family starting from any family member. `findOriginal()` returns the root original media. `findVariant('name')` returns a specific variant by name. `hasVariant('name')` checks for the existence of a variant without retrieving it. ```php findOriginal(); $variant = $media->findVariant('thumbnail'); $bool = $media->hasVariant('thumbnail'); ``` -------------------------------- ### Listing All Media Variant Family Members (Laravel Mediable, PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Demonstrates methods to retrieve a collection containing all media records belonging to the same variant family. `getAllVariants()` gets only the variants (excluding the current instance). `getAllVariantsAndSelf()` includes the current instance in the collection. The returned collection is keyed by variant name ('original' for the original). ```php getAllVariants(); // including the current model $collection = $media->getAllVariantsAndSelf(); /* outputs [ 'original' => Media{}, 'thumbnail' => Media{}, 'large' => Media{} etc. ] */ ``` -------------------------------- ### Getting Variant URL from Model (Laravel Mediable, PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Illustrates a common pattern for accessing and using image variants associated with a `Mediable` model. This snippet demonstrates retrieving a specific variant (e.g., 'thumbnail') from the media related to a post (filtered by the 'feature' tag) and then getting its public URL. ```php getMedia('feature') ->findVariant('thumbnail') ->getUrl(); ``` -------------------------------- ### Synchronizing Media Records using Artisan (bash) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/commands.rst Runs both the `media:import` and `media:prune` commands sequentially. Synchronizes database records with files on the disk in a single step. Requires specifying a disk name. ```bash $ php artisan media:sync [disk] ``` -------------------------------- ### Importing Media Records using Artisan (bash) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/commands.rst Creates database records for files existing on disk but not in the database. Applies configured type restrictions. Requires specifying a disk name. ```bash $ php artisan media:import [disk] ``` -------------------------------- ### Adding Data URL Source Adapter Configuration - Laravel PHP Source: https://github.com/plank/laravel-mediable/blob/master/UPGRADING.md Adds a regular expression pattern and the corresponding `DataUrlAdapter` class reference to the `source_adapters.pattern` array in the `config/mediable.php` file. This enables the `MediaUploader` to process and handle Data URLs as valid media sources. ```php '^data:/?/?[^,]*,' => Plank\Mediable\SourceAdapters\DataUrlAdapter::class, ``` -------------------------------- ### Configuring Default and Allowed Mediable Disks - PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/configuration.rst Specifies which filesystem disks the `laravel-mediable` package is authorized to use for media storage and sets the default disk to be used if no disk is explicitly provided during an upload or operation. ```php 'uploads', /* * Filesystems that can be used for media storage */ 'allowed_disks' => [ 'local', 'uploads', ], //... ``` -------------------------------- ### Eager Loading Media and Variants (Laravel Mediable, PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Highlights the importance of eager loading to prevent N+1 query problems when working with media and variants from a collection of `Mediable` models. Shows static methods (`withMediaAndVariants`, `withMediaAndVariantsMatchAll`) for initial queries and instance methods (`loadMediaAndVariants`, `loadMediaAndVariantsMatchAll`) for lazy eager loading on existing collections or single models, optionally filtering by tags. ```php get(); $posts = Post::withMediaAndVariantsMatchAll($tags)->get(); // lazy eager load from a collection of Mediables $posts->loadMediaAndVariants($tags); $posts->loadMediaAndVariantsMatchAll($tags); // lazy eager load from a single Mediable model $post->loadMediaAndVariants($tags); $post->loadMediaAndVariantsMatchAll($tags); ``` -------------------------------- ### Querying Media Records PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/media.rst Demonstrates static methods available on the `Media` class for querying the media table directly, useful for finding records based on directory, path, or filename. ```php copyTo('new/directory'); $newMedia = $media->copyTo('new/directory', 'new-filename'); $newMedia = $media->copyToDisk('uploads', 'new/directory', 'new-filename'); ``` -------------------------------- ### Importing String Data Laravel Mediable PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/uploader.rst This snippet demonstrates creating a Media record and uploading a file directly from a string containing the file's binary data. It typically involves obtaining the string data (e.g., by reading a file into a string or encoding an image) and then piping it through `MediaUploader::fromString()` to a specified destination for upload. ```php encode('jpg'); MediaUploader::fromString($jpg) ->toDestination(...) ->upload(); ``` -------------------------------- ### Configuring Custom Mediable Classes and Adapters - PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/configuration.rst Configures the fully qualified class names for various internal components used by `laravel-mediable`, enabling extension or replacement of default behaviors. This includes the Media model class, source adapters for different input types (e.g., UploadedFile, Stream, URL), and URL generators for different filesystem disks. ```php Plank\Mediable\Media::class, /* * List of adapters to use for various source inputs * * Adapters can map either to a class or a pattern (regex) */ 'source_adapters' => [ 'class' => [ Symfony\Component\HttpFoundation\File\UploadedFile::class => Plank\Mediable\SourceAdapters\UploadedFileAdapter::class, Symfony\Component\HttpFoundation\File\File::class => Plank\Mediable\SourceAdapters\FileAdapter::class, Psr\Http\Message\StreamInterface::class => Plank\Mediable\SourceAdapters\StreamAdapter::class, ], 'pattern' => [ '^https?://' => Plank\Mediable\SourceAdapters\RemoteUrlAdapter::class, '^/' => Plank\Mediable\SourceAdapters\LocalPathAdapter::class ], ], /* * List of URL Generators to use for handling various filesystem disks */ 'url_generators' => [ 'local' => Plank\Mediable\UrlGenerators\LocalUrlGenerator::class, 's3' => Plank\Mediable\UrlGenerators\S3UrlGenerator::class, ], //... ``` -------------------------------- ### Dispatching Async Image Variant Creation (Laravel Mediable, PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Demonstrates how to use the `CreateImageVariants` job to asynchronously process the creation of image variants. You can dispatch the job for a single `Media` model or a collection of `Media` models, specifying one or multiple variant names to generate. This is beneficial for time-consuming manipulations. ```php null, //... ``` -------------------------------- ### Performing Basic File Upload PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/uploader.rst The simplest way to upload a file is by providing the source (like an uploaded file from a request) and calling the `upload()` method. This uses the default disk and directory settings. ```php file('thumbnail'))->upload(); ``` -------------------------------- ### Pruning Media Records using Artisan (bash) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/commands.rst Deletes database records for files that no longer exist on the disk. Helps remove orphaned records. Requires specifying a disk name. ```bash $ php artisan media:prune [disk] ``` -------------------------------- ### Accessing Media File Paths and Attributes PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/media.rst Demonstrates various methods and attributes on a `Media` instance to retrieve different representations of its file path, directory, filename, and extension. ```php $media->getAbsolutePath(); // /var/www/site/public/uploads/foo/bar/picture.jpg $media->getDiskPath(); // foo/bar/picture.jpg $media->directory; // foo/bar $media->basename; // picture.jpg $media->filename; // picture $media->extension; // jpg ``` -------------------------------- ### Using a Before-Save Callback for Variant Media Record (PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Register a callback function using `beforeSave` that executes just before the new Media record for the variant is saved to the database. This callback receives the populated Media model instance, allowing modification of its properties (e.g., directory, custom fields) before persistence. ```php beforeSave(function(Media $media) { $media->directory = 'thumbnails'; $media->someOtherField = 'potato'; }); ``` -------------------------------- ### Adding Filesystem Adapter Options PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/uploader.rst Pass an array of additional options directly to the underlying filesystem adapter when storing the file. This is useful for setting adapter-specific configurations like caching headers for S3. ```php file('image')) ->withOptions(['Cache-Control' => 'max-age=3600']) ->upload(); ``` -------------------------------- ### Configuring Mediable Upload Validation Rules - PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/configuration.rst Sets default validation options for media uploads within the `laravel-mediable` package. Includes configurations for maximum file size, behavior when a duplicate file is detected (increment, replace, error), and strictness rules for type checking based on MIME types and extensions. ```php 1024 * 1024 * 10, /* * What to do if a duplicate file is uploaded. Options include: * * * 'increment': the new file's name is given an incrementing suffix * * 'replace' : the old file and media model is deleted * * 'error': an Exception is thrown * */ 'on_duplicate' => Plank\Mediable\MediaUploader::ON_DUPLICATE_INCREMENT, /* * Reject files unless both their mime and extension are recognized and both match a single aggregate type */ 'strict_type_checking' => false, /* * Reject files whose mime type or extension is not recognized * if true, files will be given a type of `'other'` */ 'allow_unrecognized_types' => false, /* * Only allow files with specific MIME type(s) to be uploaded */ 'allowed_mime_types' => [], /* * Only allow files with specific file extension(s) to be uploaded */ 'allowed_extensions' => [], /* * Only allow files matching specific aggregate type(s) to be uploaded */ 'allowed_aggregate_types' => [], //... ``` -------------------------------- ### Configuring Prefer Client MIME Type Option - Laravel PHP Source: https://github.com/plank/laravel-mediable/blob/master/UPGRADING.md Adds the `prefer_client_mime_type` boolean option to the `config/mediable.php` file. When set to `true`, the library prioritizes the MIME type provided by the client; when `false` (default), it always infers the type from the file contents. ```php 'prefer_client_mime_type' => false, ``` -------------------------------- ### Customizing Output Destination for Image Variants (PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Specify the filesystem disk and directory where the generated variant file should be saved using the `toDisk`, `toDirectory`, or the combined `toDestination` methods. By default, variants are saved to the same disk and directory as the original media. ```php toDisk('uploads'); $manipulation->toDirectory('files/variants'); // shorthand for the above $manipulation->toDestination('uploads', 'files/variants'); ``` -------------------------------- ### Specifying Upload Destination PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/uploader.rst Customize the destination disk and directory for the uploaded file. You can set the disk and directory separately or together using the `toDisk()`, `toDirectory()`, or `toDestination()` methods before calling `upload()`. ```php file('thumbnail')) // specify a disk to use instead of the default ->toDisk('s3'); // place the file in a directory relative to the disk root ->toDirectory('user/john/profile') // alternatively, specify both the disk and directory at once ->toDestination('s3', 'user/john/profile') ->upload(); ``` -------------------------------- ### Generating Public URLs for Media PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/media.rst Shows how to generate a public URL for a media file. This method requires the media file to be stored on a public disk and have public visibility set, otherwise it will throw an exception. ```php $media->getUrl(); // http://localhost/uploads/foo/bar/picture.jpg ``` -------------------------------- ### Generating Temporary Signed URLs for Private Media PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/media.rst Illustrates how to generate a temporary, signed URL for a private media file stored on an Amazon S3 disk, allowing authorized access for a limited duration. Requires Carbon for the expiration time. ```php getTemporaryUrl(Carbon::now->addMinutes(5)); ``` -------------------------------- ### Deleting Media Record and File PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/media.rst Shows the standard Eloquent `delete()` method on a `Media` instance, which correctly deletes both the database record and the associated file from the disk. ```php delete(); ``` -------------------------------- ### Setting Media File Visibility PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/media.rst Demonstrates how to update the visibility setting of a media file on its storage disk, allowing you to change it between public and private. ```php makePublic(); $media->makePrivate(); ``` -------------------------------- ### Moving and Renaming Media Files PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/media.rst Shows methods for changing the location or filename of a media file on disk. Moving a file updates the corresponding `Media` record's path attributes. ```php move('new/directory'); $media->move('new/directory', 'new-filename'); $media->rename('new-filename'); $media->moveToDisk('uploads', 'new/directory', 'new-filename'); ``` -------------------------------- ### Configuring Intervention/Image >=3.0 Driver in Laravel Service Container (PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Manually bind the appropriate driver interface for intervention/image version 3.0 or higher in a Laravel service provider's register method. This configures the library to use either the GD or Imagick PHP extension for image processing, which is a prerequisite for using laravel-mediable's image manipulation features. ```php bind(Intervention\Image\Interfaces\DriverInterface::class, \Intervention\Image\Drivers\Gd\Driver::class ); // if using Imagick $app->bind(Intervention\Image\Interfaces\DriverInterface::class, \Intervention\Image\Drivers\Imagick\Driver::class ); } } ``` -------------------------------- ### Manually Adjusting Media Variant Relationships (Laravel Mediable, PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Explains how to manually modify the relationship between media records. `makeOriginal()->save()` promotes a variant to become a new original, detaching it from its previous family. `makeVariantOf($otherMedia, 'small')->save()` or `makeVariantOf($otherMediaId, 'small')->save()` assigns the current media as a variant of another existing media record. ```php makeOriginal()->save(); To manually indicate that one ``Media`` record is a variant of another :: makeVariantOf($otherMedia, 'small')->save(); $media->makeVariantOf($otherMediaId, 'small')->save(); ``` -------------------------------- ### Defining Image Variants with ImageManipulator in Laravel (PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Define image manipulation variants using the `ImageManipulator` facade, typically in a service provider's `boot` method. Each variant is given a name and an `ImageManipulation` instance containing a callback that uses the Intervention/Image API to perform transformations like fitting or greyscale. ```php fit(32, 32); })->outputPngFormat() ); ImageManipulator::defineVariant( 'bw-square', ImageManipulation::make(function (Image $image, Media $originalMedia) { $image->fit(128, 128)->greyscale(); }) ); } } ``` -------------------------------- ### Configuring Duplicate Filename Handling for Variants (PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Determine how the system should handle filename conflicts when saving a variant. `onDuplicateIncrement` (the default) appends an incrementing number, while `onDuplicateError` will throw an exception if a file with the same name exists at the target destination. ```php onDuplicateIncrement(); // default behaviour $manipulation->onDuplicateError(); ``` -------------------------------- ### Setting Output Formats for Image Manipulations (PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Use fluent methods on the `ImageManipulation` object to specify the desired output format for the manipulated image file. Available methods cover common formats like JPEG, PNG, GIF, TIFF, BMP, WebP, and HEIC, or a custom format can be set. ```php outputJpegFormat(); $manipulation->outputPngFormat(); $manipulation->outputGifFormat(); $manipulation->outputTiffFormat(); $manipulation->outputBmpFormat(); $manipulation->outputWebpFormat(); $manipulation->outputHeicFormat(); $manipulation->setOutputFormat($format); ``` -------------------------------- ### Controlling Image Optimization for Manipulations (PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Manage post-manipulation image optimization using methods on the `ImageManipulation` object. You can disable optimization, enable it using the default configuration, or enable it while providing an array to override the specific optimizers and their arguments for this manipulation. ```php noOptimization(); // enable optimization for this manipulation $manipulation->optimize(); // enable optimization but override the optimizers to be applied $manipulation->optimize([Pngquant::class => ['--quality=65']]); ``` -------------------------------- ### Setting File Visibility for Image Variants (PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Set the filesystem visibility ('public' or 'private') for the newly created variant file. The `matchOriginalVisibility` method can also be used to apply the same visibility settings as the original media file. ```php makePrivate(); $manipulation->makePublic(); // to copy the visibility of the original media file $manipulation->matchOriginalVisibility(); ``` -------------------------------- ### Creating an Image Variant from Original Media (PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Generate a specific image variant from an existing Media record using the `ImageManipulator::createImageVariant` method. This method applies the previously defined manipulation for the given variant name, saves the resulting file, and creates a new Media record representing the variant. ```php useHashForFilename() // default is 'md5' ->useHashForFilename('sha1') ->upload(); ``` -------------------------------- ### Replacing Existing Media File Laravel Mediable PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/uploader.rst This snippet shows how to replace the physical file associated with an existing Media record while keeping the same database record and any model associations intact. It finds the target Media record and then uses the `replace()` method on a new upload source to swap the files. ```php replace($media); ``` -------------------------------- ### Identifying Media Original vs. Variant (Laravel Mediable, PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Provides methods available on a `Media` model instance to determine its status within a variant family. You can check if it's the original (`isOriginal`), any type of variant (`isVariant`), a specific variant by name (`isVariant('name')`), or retrieve the variant name itself (`variant_name`, which is null for originals). ```php isOriginal(); // check if the Media is any kind of variant $media->isVariant(); // check if the Media is a specific kind of variant $media->isVariant('thumbnail'); // read the kind of the variant, will be `null` for originals $media->variant_name; ``` -------------------------------- ### Configuring Intervention/Image <3.0 Manager in Laravel Service Container (PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Manually bind the ImageManager class for intervention/image versions older than 3.0 in a Laravel service provider's register method. This sets up the ImageManager instance with the specified driver ('imagick' or 'gd') for use within the application and by the laravel-mediable package. ```php app->bind( ImageManager::class, function() { return new ImageManager(['driver' => 'imagick']); // return new ImageManager(['driver' => 'gd']); } ); } } ``` -------------------------------- ### Querying Media by Aggregate Type (PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/types.rst This snippet demonstrates how to retrieve media records from the database by filtering on the `aggregate_type` column. It uses the `Media::TYPE_IMAGE` constant, which groups various image file types under a single category, making it easy to find all images regardless of their specific format (e.g., JPEG, PNG, GIF). ```php get(); ``` -------------------------------- ### Setting Output Quality for Lossy Image Formats (PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Control the compression level for lossy output formats like JPEG, TIFF, WEBP, and HEIC using the `setOutputQuality` method. The quality parameter ranges from 0 (lowest quality, smallest file) to 100 (highest quality, largest file), defaulting to 90 if not specified. ```php outputJpegFormat()->setOutputQuality(50); $manipulation->outputHeicFormat()->setOutputQuality(50); ``` -------------------------------- ### Defining and Generating Tagged Variants (Laravel Mediable, PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Shows how to group variant definitions using tags during the `ImageManipulator::defineVariant` call. Once defined, you can retrieve all variant names associated with a specific tag using `ImageManipulator::getVariantNamesByTag` and pass this collection of names to the `CreateImageVariants::dispatch` job to generate all variants defined with that tag for a given media collection. ```php onDuplicateIncrement(); // replace old file with new one, update existing Media record, maintain associations $uploader->onDuplicateUpdate(); // replace old file and media record with new ones, break associations $uploader->onDuplicateReplace(); // replace old file and media record with new ones, break associations // will also delete any existing variants of the replaced media record $uploader->onDuplicateReplaceWithVariants(); // cancel upload, throw an exception $uploader->onDuplicateError(); ``` -------------------------------- ### Applying Image Manipulations During Upload PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/uploader.rst Apply image manipulations synchronously during the upload process using the `intervention/image` library. You can pass an `ImageManipulation` instance configured with a closure or reference a registered variant name. ```php fit(100, 100); })->outputPngFormat(); $media = MediaUploader::fromSource($request->file('image')) ->applyImageManipulation($manipulation); ->upload(); ``` ```php file('image')) ->applyImageManipulation('thumbnail') ->upload(); ``` -------------------------------- ### Adding Alt Text Attribute PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/uploader.rst Record alternate text for the media record associated with the uploaded file. Use the `withAltAttribute()` method, passing the desired alt text string. ```php withAltAttribute('This is the alt text') ->upload(); ``` -------------------------------- ### Query Builder Delete (File Not Deleted) PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/media.rst Highlights the distinction that using the `delete()` method directly on the query builder will delete database records but *not* delete the associated files from disk. ```php delete(); //will not delete files ``` -------------------------------- ### Transforming MediaUploadException in Handler PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/uploader.rst Use the `HandlesMediaUploadExceptions` trait in your `App\Exceptions\Handler` to automatically transform `MediaUploadException` instances into appropriate `HttpException` responses with relevant status codes. ```php transformMediaUploadException($e); return parent::render($request, $e); } } ``` -------------------------------- ### Forcing Image Variant Recreation (Laravel Mediable, PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Explains how to force the regeneration of an image variant if one with the same name already exists. By default, existing variants are skipped. Passing `true` as the third parameter to `ImageManipulator::createImageVariant` or `CreateImageVariants::dispatch` forces the deletion of the old variant file and creation of a new one. ```php file('image')) // model class to use ->setModelClass(CustomMediaClass::class) // pass the callable ->beforeSave(function (Media $model, SourceAdapterInterface $source) { $model->setAttribute('customAttribute', 'value'); }) ->upload(); ``` -------------------------------- ### Adding Order Column to Mediables Table - Laravel PHP Source: https://github.com/plank/laravel-mediable/blob/master/UPGRADING.md Provides a code snippet for a Laravel migration to add an `order` column to the `mediables` table. The column is defined as an unsigned integer and an index is added to it. This is required when upgrading from version 1.x to 2.x. ```php $table->integer('order')->unsigned()->index(); ``` -------------------------------- ### Handling MediaUploadException in Controller PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/uploader.rst Catch a `MediaUploadException` in a controller and use the `HandlesMediaUploadExceptions` trait's `transformMediaUploadException` method to convert it into an `HttpException` with a specific HTTP status code before re-throwing. ```php file('file')) ->toDestination(...) ->upload(); }catch(MediaUploadException $e){ throw $this->transformMediaUploadException($e); } } } ``` -------------------------------- ### Setting File Visibility During Upload PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/uploader.rst Control whether the uploaded file should be publicly accessible on the filesystem. Use `makePublic()` (default) or `makePrivate()` to set the visibility. ```php file('image')) ->makePrivate() // Disable public access ->makePublic() // Default behaviour ->upload(); ``` -------------------------------- ### Validating File Without Uploading PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/uploader.rst Perform validation checks on a file source without proceeding with the actual file transfer or database record creation. Use the `verifyFile()` method; an exception is thrown if validation fails. ```php file('image')) // model class to use ->setModelClass(MediaSubclass::class) // maximum filesize in bytes ->setMaximumSize(99999) // only allow files of specific MIME types ->setAllowedMimeTypes(['image/jpeg']) ->verifyFile(); ``` -------------------------------- ### Customizing Output Filename for Image Variants (PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/variants.rst Control the filename of the output variant file. Methods allow setting a specific filename, generating a filename based on a hash (defaulting to MD5), or reverting to the default behavior which appends the variant name to the original filename. ```php useFilename('my-custom-filename'); $manipulation->useHashForFilename(); // defaults to md5 $manipulation->useHashForFilename('sha1'); $manipulation->useOriginalFilename(); //restore default behaviour ``` -------------------------------- ### Restricting Uploads by Aggregate Type (PHP) Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/types.rst This code shows how to configure the `MediaUploader` to only accept files belonging to specific aggregate types during the upload process. It sets the allowed types to `Media::TYPE_IMAGE` and `Media::TYPE_IMAGE_VECTOR`, ensuring only standard images or vector images can be uploaded via this process. ```php file('thumbnail')) ->toDestination('uploads', '') ->setAllowedAggregateTypes([Media::TYPE_IMAGE, Media::TYPE_IMAGE_VECTOR]) ->upload() ``` -------------------------------- ### Deleting Media Records PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/mediable.rst Illustrates the default behavior when deleting `Media` records using the `delete()` method in PHP. By default, this operation does not detach the associated relationships with other models. Detachment requires specific configuration or using `forceDelete()` if soft deletes are enabled. ```php delete(); //will not detach relationships ``` -------------------------------- ### Setting Custom Filename PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/uploader.rst Override the original filename of the source file by providing a custom name using the `useFilename()` method before the upload. ```php useFilename('profile') ->upload(); ``` -------------------------------- ### Updating Media Record Attributes Laravel Mediable PHP Source: https://github.com/plank/laravel-mediable/blob/master/docs/source/uploader.rst This snippet explains how to update the stored attributes of a Media record based on the current state of its associated file on disk. The `update()` method recalculates and saves the `mime_type`, `aggregate_type`, and `size` attributes if they differ from the current database values. ```php file('image')) // model class to use ->setModelClass(MediaSubclass::class) // maximum filesize in bytes ->setMaximumSize(99999) // whether the aggregate type must match both the MIME type and extension ->setStrictTypeChecking(true) // whether to allow the 'other' aggregate type ->setAllowUnrecognizedTypes(true) // only allow files of specific MIME types ->setAllowedMimeTypes(['image/jpeg']) // only allow files of specific extensions ->setAllowedExtensions(['jpg', 'jpeg']) // only allow files of specific aggregate types ->setAllowedAggregateTypes(['image']) // ensure that the file contents match a provided hash // second argument is the hash algorithm to use // supports any algorithm supported by PHP's hash() function ->validateHash('3ef5e70366086147c2695325d79a25cc', 'md5') ->validateHash('5e96e1fa58067853219c4cb6d3c1ce01cc5cc8ce', 'sha1') ->upload(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.