### Load and Display Attached Media Source: https://laravel-mediable.readthedocs.io/en/latest/installation This example demonstrates how to load media associated with a model using `withMedia()`, retrieve a specific media item by its relation name, and get its URL. ```php find($postId); echo $post->getMedia('thumbnail')->first()->getUrl(); ``` -------------------------------- ### Upload Files using MediaUploader Source: https://laravel-mediable.readthedocs.io/en/latest/installation This example demonstrates how to upload a file from a request, specifying the destination (e.g., S3), and converting it into a Media record using the MediaUploader facade. ```php file('thumbnail')) ->toDestination('s3', 'posts/thumbnails') ->upload(); ``` -------------------------------- ### Run Laravel Mediable Database Migrations Source: https://laravel-mediable.readthedocs.io/en/latest/installation Execute this Artisan command to run the package's database migrations, creating the necessary tables for storing media information in your application. ```bash $ php artisan migrate ``` -------------------------------- ### Install Laravel Mediable using Composer Source: https://laravel-mediable.readthedocs.io/en/latest/installation This command adds the plank/laravel-mediable package to your Laravel project's dependencies. Ensure you have Composer installed and configured for your project. ```bash $ composer require plank/laravel-mediable ``` -------------------------------- ### Publish Laravel Mediable Assets Source: https://laravel-mediable.readthedocs.io/en/latest/installation Use the Artisan command to publish the package's configuration file (config/mediable.php) and migration file. This allows customization of package settings and database schema. ```bash $ php artisan vendor:publish --provider="Plank\Mediable\MediableServiceProvider" ``` -------------------------------- ### Attach Media to Eloquent Model Source: https://laravel-mediable.readthedocs.io/en/latest/installation This snippet shows how to attach a Media record to an Eloquent model instance. The second argument can be used to define a relationship name for the attached media. ```php attachMedia($media, 'thumbnail'); ``` -------------------------------- ### Integrate Mediable Trait into Eloquent Model Source: https://laravel-mediable.readthedocs.io/en/latest/installation Add the Mediable trait and MediableInterface to your Eloquent model to enable media attachment capabilities. This requires importing the necessary classes. ```php [ //... 'MediaUploader' => Plank\Mediable\Facades\MediaUploader::class, //... ] ``` -------------------------------- ### Register Laravel Mediable Service Provider Source: https://laravel-mediable.readthedocs.io/en/latest/installation This snippet shows how to register the MediableServiceProvider in your Laravel application's configuration file (config/app.php). This step is automatic for Laravel 5.5+ if package auto-discovery is enabled. ```php 'providers' => [ //... Plank\Mediable\MediableServiceProvider::class, //... ]; ``` -------------------------------- ### Retrieving Media by Tag Source: https://laravel-mediable.readthedocs.io/en/latest/mediable Illustrates how to retrieve media attached to a model using tag names. It includes methods for getting all media for a tag, the first or last media, and handling multiple tags with options for matching all or any. ```php getMedia('thumbnail'); $media = $post->firstMedia('thumbnail'); $post->getMedia(['header', 'footer']); // get media with either tag $post->getMedia(['header', 'footer'], true); //get media with both tags $post->getMediaMatchAll(['header', 'footer']); //alias $post->getAllMediaByTag(); ``` -------------------------------- ### Automatic Media Rehydration Example (PHP) Source: https://laravel-mediable.readthedocs.io/en/latest/mediable Illustrates automatic media rehydration. After attaching media to the 'gallery' tag, subsequent calls to `getMedia('gallery')` will perform a `loadMedia()` to reflect the changes, while `getMedia('thumbnail')` remains unaffected. ```php loadMedia(); $post->getMedia('gallery'); // returns an empty collection $post->getMedia('thumbnail'); // returns an empty collection $post->attachMedia($media, 'gallery'); // marks the gallery tag as dirty $post->getMedia('thumbnail'); // still returns an empty collection $post->getMedia('gallery'); // performs a `loadMedia()`, returns a collection with $media ``` -------------------------------- ### Lazy Eager Load Media and Variants with 'loadMediaWithVariants()' (PHP) Source: https://laravel-mediable.readthedocs.io/en/latest/mediable Provides examples of lazy eager loading media and their variants for a collection of models or a single model instance, with options to filter by tags. Uses `loadMediaWithVariants()` and `loadMediaWithVariantsMatchAll()`. ```php loadMediaWithVariants($tags); $posts->loadMediaWithVariantsMatchAll($tags); // lazy eager load from a single Mediable model $post->loadMediaWithVariants($tags); $post->loadMediaWithVariantsMatchAll($tags); ``` -------------------------------- ### Navigate Between Media Variants Source: https://laravel-mediable.readthedocs.io/en/latest/variants Find the original media from a variant, find a specific variant from any media in the family, or check if a specific variant exists. It's recommended to start navigation from a consistent point to avoid extra database queries. ```php findOriginal(); $variant = $media->findVariant('thumbnail'); $bool = $media->hasVariant('thumbnail'); ``` -------------------------------- ### Control Image Optimization with Laravel Mediable Manipulations Source: https://laravel-mediable.readthedocs.io/en/latest/variants Demonstrates how to control image optimization settings for individual manipulations using the ImageManipulator. This includes disabling, enabling, or overriding default optimizers and their arguments. Ensure optimizer binaries are installed and configured in `config/mediable.php`. ```php noOptimization(); // enable optimization for this manipulation $manipulation->optimize(); // enable optimization but override the optimizers to be applied $manipulation->optimize([Pngquant::class => ['--quality=65']]); ``` -------------------------------- ### Handle Media Upload Exceptions in Controller - PHP Source: https://laravel-mediable.readthedocs.io/en/latest/uploader This example shows how to apply the HandlesMediaUploadExceptions trait directly to a controller. This is useful when you want specific actions within a controller to throw an HttpException for media upload errors, allowing for localized exception handling without affecting the entire application's exception handler. ```PHP file('file')) ->toDestination(...) ->upload(); }catch(MediaUploadException $e){ throw $this->transformMediaUploadException($e); } } } ``` -------------------------------- ### Detaching Media from a Model Source: https://laravel-mediable.readthedocs.io/en/latest/mediable Provides examples of how to remove media associations from a model, either entirely or for specific tags. It also covers detaching all media associated with one or more tags. ```php detachMedia($media); // remove media from all tags $post->detachMedia($media, 'feature'); //remove media from specific tag $post->detachMedia($media, ['feature', 'thumbnail']); //remove media from multiple tags $post->detachMediaTags('feature'); $post->detachMediaTags(['feature', 'thumbnail']); ``` -------------------------------- ### Define Custom Aggregate File Types Source: https://laravel-mediable.readthedocs.io/en/latest/configuration This PHP snippet shows how to define custom aggregate file types in `config/mediable.php`. It provides an example of creating a 'markup' aggregate type that includes various markup-related MIME types and file extensions. ```php [ //... 'markup' => [ 'mime_types' => [ 'text/markdown', 'text/html', 'text/xml', 'application/xml', 'application/xhtml+xml', ], 'extensions' => [ 'md', 'html', 'htm', 'xhtml', 'xml' ] ], //... ] //... ``` -------------------------------- ### Get URL of a Specific Image Variant Source: https://laravel-mediable.readthedocs.io/en/latest/variants Retrieve the URL for a specific variant of a media item associated with a model. This is useful for displaying derived images in views. ```php getMedia('feature') ->findVariant('thumbnail') ->getUrl() ``` -------------------------------- ### Basic File Upload with MediaUploader Facade Source: https://laravel-mediable.readthedocs.io/en/latest/uploader Demonstrates the simplest way to upload a file using the MediaUploader facade. It takes a file from the request, uploads it to the default disk, and returns a Media record. Dependencies include the MediaUploader facade and the request object. ```php file('thumbnail'))->upload(); ``` -------------------------------- ### Eager Load Media by Tags with 'withMedia()' (PHP) Source: https://laravel-mediable.readthedocs.io/en/latest/mediable Shows how to eager load media specifically tagged as 'thumbnail' or 'featured' for a collection of posts using `withMedia()`. It also demonstrates loading media that matches all specified tags using `withMediaMatchAll()`. ```php get(); // attached to either tags $posts = Post::withMediaMatchAll(['thumbnail', 'featured'])->get(); // attached to both tags ``` -------------------------------- ### Accessing Media Attributes and Paths - PHP Source: https://laravel-mediable.readthedocs.io/en/latest/media Demonstrates how to access attributes like disk, directory, filename, and extension from a Media instance. It also shows how to generate absolute paths, disk-relative paths, and basenames for the media file. ```php 'uploads', // 'directory' => 'foo/bar', // 'filename' => 'picture', // 'extension' => 'jpg' // ] $media->getAbsolutePath(); // Expected output: /var/www/site/public/uploads/foo/bar/picture.jpg $media->getDiskPath(); // Expected output: foo/bar/picture.jpg echo $media->directory; // Expected output: foo/bar echo $media->basename; // Expected output: picture.jpg echo $media->filename; // Expected output: picture echo $media->extension; // Expected output: jpg ``` -------------------------------- ### Configure Filesystem Disks for Laravel-Mediable Source: https://laravel-mediable.readthedocs.io/en/latest/configuration This snippet shows how to configure local and custom 'uploads' disks in Laravel's `config/filesystems.php` to be used by Laravel-Mediable. It defines the driver, root path, URL, and visibility for each disk. ```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' ], ] //... ``` -------------------------------- ### Specifying Destination Disk and Directory for Uploads Source: https://laravel-mediable.readthedocs.io/en/latest/uploader Shows how to customize the upload destination by specifying a different disk and directory. The `toDisk()`, `toDirectory()`, and `toDestination()` methods allow fine-grained control over where the file is stored. This is useful for organizing files across different storage configurations. ```php file('thumbnail')) ->toDisk('s3') ->toDirectory('user/john/profile') ->upload(); // Alternatively, specify both at once $uploader = MediaUploader::fromSource($request->file('thumbnail')) ->toDestination('s3', 'user/john/profile') ->upload(); ``` -------------------------------- ### Import Existing Files to Media - PHP Source: https://laravel-mediable.readthedocs.io/en/latest/uploader These methods allow you to create a media record for a file that already exists on a specified filesystem disk. `import` requires the disk, directory, filename, and extension, while `importPath` simplifies this by taking the full path to the file. ```PHP loadMedia(['thumbnail', 'featured']); // attached to either tag $posts->loadMediaMatchAll(['thumbnail', 'featured']); // attached to both tags ``` -------------------------------- ### Moving and Renaming Media Files - PHP Source: https://laravel-mediable.readthedocs.io/en/latest/media Explains how to change the location and filename of a media file on disk using the `move` and `rename` methods. It also shows how to move media to a different disk. ```php move('new/directory'); // Move the media file to a new directory with a new filename. $media->move('new/directory', 'new-filename'); // Rename the media file. $media->rename('new-filename'); // Move the media file to a specific disk, directory, and filename. $media->moveToDisk('uploads', 'new/directory', 'new-filename'); ``` -------------------------------- ### Eager Load Media and Variants with 'withMediaAndVariants()' (PHP) Source: https://laravel-mediable.readthedocs.io/en/latest/mediable Demonstrates eager loading both media and their associated variants for a collection of posts, optionally filtering by specific tags. Uses `withMediaAndVariants()` and `withMediaAndVariantsMatchAll()`. ```php get(); Post::withMediaAndVariantsMatchAll($tags)->get(); ``` -------------------------------- ### Querying Media Records Directly - PHP Source: https://laravel-mediable.readthedocs.io/en/latest/media Illustrates how to query the Media database table directly using static methods on the Media class. This allows filtering media based on directory, path, or filename. ```php syncMedia($media, 'thumbnail'); ``` -------------------------------- ### Authorize Disks and Set Default Disk in Laravel-Mediable Source: https://laravel-mediable.readthedocs.io/en/latest/configuration This snippet demonstrates how to configure `config/mediable.php` to specify the default filesystem disk for media storage and list all allowed disks that the package can utilize. ```php 'uploads', /* * Filesystems that can be used for media storage */ 'allowed_disks' => [ 'local', 'uploads', ], //... ``` -------------------------------- ### Reordering Media with syncMedia() Source: https://laravel-mediable.readthedocs.io/en/latest/mediable Explains how to reorder media associated with a tag by manipulating the Eloquent collection and then using `syncMedia()` to persist the changes. This maintains the order of media. ```php getMedia('gallery'); $media = $media->prepend($new_media); $post->syncMedia($media, 'gallery'); ``` -------------------------------- ### Import Media Files with Artisan Source: https://laravel-mediable.readthedocs.io/en/latest/commands Creates media records in the database for files on disk that lack records. This command respects type restrictions defined in the mediable configuration file. It takes an optional disk name as an argument. ```bash $ php artisan media:import [disk] ``` -------------------------------- ### Copying Media Files - PHP Source: https://laravel-mediable.readthedocs.io/en/latest/media Demonstrates how to duplicate a media file to a different location on disk using the `copyTo()` method. This operation creates a new Media record for the copied file. It also shows copying to a different disk. ```php copyTo('new/directory'); // Copy the media file to a new directory with a new filename. $newMedia = $media->copyTo('new/directory', 'new-filename'); // Copy the media file to a specific disk, directory, and filename. $newMedia = $media->copyToDisk('uploads', 'new/directory', 'new-filename'); ``` -------------------------------- ### Validate and Upload Files with Custom Configurations - PHP Source: https://laravel-mediable.readthedocs.io/en/latest/uploader Demonstrates how to upload a file using MediaUploader from a source file, applying various custom validation rules and model configurations. This includes setting the model class, maximum size, strict type checking, allowed MIME types and extensions, and validating file hashes. It throws a `MediaUploadException` if any validation fails. ```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(); ``` -------------------------------- ### Avoid N+1 Problem with Basic Media Loading (PHP) Source: https://laravel-mediable.readthedocs.io/en/latest/mediable Demonstrates the N+1 problem when loading media for multiple posts without eager loading. This results in an excessive number of database queries, impacting performance. ```php get(); foreach($posts as $post){ echo $post->firstMedia('thumbnail')->getUrl(); } ``` -------------------------------- ### Pass Filesystem Adapter Options - PHP Source: https://laravel-mediable.readthedocs.io/en/latest/uploader Shows how to pass additional option flags directly to the underlying filesystem adapter during the upload process. This is particularly useful for cloud storage services like S3, allowing for configurations such as setting cache control headers. ```php file('image')) ->withOptions(['Cache-Control' => 'max-age=3600']) ->upload(); ``` -------------------------------- ### Lazy Eager Load All Media with 'loadMedia()' (PHP) Source: https://laravel-mediable.readthedocs.io/en/latest/mediable Illustrates lazy eager loading of media for an existing collection of posts using the `loadMedia()` method, which is an alias for Eloquent Collection's `load('media')`. ```php load('media'); // or $posts->loadMedia(); ``` -------------------------------- ### Lazy Eager Load Media on Single Model with 'loadMedia()' (PHP) Source: https://laravel-mediable.readthedocs.io/en/latest/mediable Demonstrates lazy loading media for a single model instance using `loadMedia()`, `loadMedia()`, `loadMediaMatchAll()`. This is useful when a relationship has not been loaded previously. ```php loadMedia(); $post->loadMedia(['thumbnail', 'featured']); // attached to either tag $post->loadMediaMatchAll(['thumbnail', 'featured']); // attached to both tags ``` -------------------------------- ### Set Output Formats for Image Manipulations Source: https://laravel-mediable.readthedocs.io/en/latest/variants Demonstrates methods for specifying the output format (e.g., JPEG, PNG, WebP) and quality for image manipulations. These methods are chained after defining the manipulation callback. ```php outputJpegFormat(); $manipulation->outputPngFormat(); $manipulation->outputGifFormat(); $manipulation->outputTiffFormat(); $manipulation->outputBmpFormat(); $manipulation->outputWebpFormat(); $manipulation->setOutputFormat($format); ``` ```php outputJpegFormat()->setOutputQuality(50); ``` -------------------------------- ### Attaching Media to a Model Source: https://laravel-mediable.readthedocs.io/en/latest/mediable Demonstrates attaching single or multiple media instances to a model, optionally associating them with specific tags. Supports various input types for media like IDs, objects, or collections. ```php attachMedia($media, 'thumbnail'); $post->attachMedia([$media1->getKey(), $media2->getKey()], 'gallery'); $post->attachMedia($media, ['gallery', 'featured']); ``` -------------------------------- ### Setting Media Visibility - PHP Source: https://laravel-mediable.readthedocs.io/en/latest/media Shows how to change the visibility of a media file's storage on disk. The `makePublic()` method sets visibility to public, while `makePrivate()` sets it to private. ```php makePublic(); // Make the media file private. $media->makePrivate(); ``` -------------------------------- ### Synchronize Media Files and Records with Artisan Source: https://laravel-mediable.readthedocs.io/en/latest/commands Performs both the media import and prune operations together. This command ensures that the database records are fully synchronized with the actual media files on the specified disk. It accepts an optional disk name. ```bash $ php artisan media:sync [disk] ``` -------------------------------- ### Verify File Before Upload - PHP Source: https://laravel-mediable.readthedocs.io/en/latest/uploader Shows how to validate a file using `verifyFile()` without actually uploading it. This method performs the same validation checks as the upload process. If the file fails validation, a `PlankMediableMediaUploadException` is thrown, indicating the reason for rejection. ```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() ``` -------------------------------- ### Queue Asynchronous Image Variant Creation with Laravel Mediable Jobs Source: https://laravel-mediable.readthedocs.io/en/latest/variants Demonstrates how to use the `CreateImageVariants` job to process the creation of image variants asynchronously. This is beneficial for large files or complex manipulations. It supports creating single or multiple variants for one or more media records in a single job. ```php true, ``` -------------------------------- ### Execute Before Save Callback for Image Manipulations in Laravel Mediable Source: https://laravel-mediable.readthedocs.io/en/latest/variants Illustrates how to define a callback function that executes after image manipulation but before the file is saved to disk and a database record is created. The callback receives the `Media` object and can be used to modify its properties or set additional fields. ```php beforeSave(function(Media $media) { $media->directory = 'thumbnails'; $media->someOtherField = 'potato'; }); ``` -------------------------------- ### List All Variants in a Family Source: https://laravel-mediable.readthedocs.io/en/latest/variants Retrieve all variants and optionally the original media record for a given media item. This can be returned as a keyed dictionary, with an option to include or exclude the current media item. ```php getAllVariants(); // including the current model $collection = $media->getAllVariantsAndSelf(); /* outputs [ 'original' => Media{}, 'thumbnail' => Media{}, 'large' => Media{} etc. ] */ ``` -------------------------------- ### Generating Public and Temporary URLs for Media - PHP Source: https://laravel-mediable.readthedocs.io/en/latest/media Shows how to generate a public URL for a Media file if it's stored on a public disk and has public visibility. It also demonstrates generating a temporary signed URL for private files on S3, valid for a specified duration. ```php getUrl(); // Expected output: http://localhost/uploads/foo/bar/picture.jpg // Check if the media is publicly accessible. $media->isPubliclyAccessible(); // Generate a temporary signed URL for private files on S3. use Carbon\Carbon; $media->getTemporaryUrl(Carbon::now()->addMinutes(5)); ``` -------------------------------- ### Eager Load All Media with 'withMedia()' (PHP) Source: https://laravel-mediable.readthedocs.io/en/latest/mediable Uses the `withMedia()` method to eager load all associated media for a collection of posts, preventing the N+1 problem. This is an alias for Eloquent's `with('media')`. ```php get(); // or $posts = Post::withMedia()->get(); ``` -------------------------------- ### Configure Media Model and Source Adapters in Laravel-Mediable Source: https://laravel-mediable.readthedocs.io/en/latest/configuration This configuration file allows customization of Laravel-Mediable's internal behavior. You can specify a custom media model extending the default `PlankMediableMedia` class and define adapters for different source input types, including classes like `UploadedFile` and patterns like URLs and local paths. ```php PlankMediableMedia::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 => PlankMediableSourceAdaptersUploadedFileAdapter::class, Symfony\Component\HttpFoundation\File\File::class => PlankMediableSourceAdaptersFileAdapter::class, Psr\Http\Message\StreamInterface::class => PlankMediableSourceAdaptersStreamAdapter::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, ], ``` -------------------------------- ### Configure Intervention/image Driver (>=3.0) Source: https://laravel-mediable.readthedocs.io/en/latest/variants Manually binds the Intervention/image driver to the service container. Supports GD or Imagick. This is an alternative to using the intervention/image-laravel package. ```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 ); } } ``` -------------------------------- ### Create Image Variants with Laravel Mediable ImageManipulator Source: https://laravel-mediable.readthedocs.io/en/latest/variants Shows how to generate a new image file (variant) from an existing media file using the `ImageManipulator::createImageVariant` method. This process also creates a new `Media` record to represent the variant. ```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); ``` -------------------------------- ### Streaming Private Media Files - PHP Source: https://laravel-mediable.readthedocs.io/en/latest/media Provides a method to stream private media files from the server to authorized users. It reads the file in chunks and returns a response suitable for downloading. ```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 ] ); ``` -------------------------------- ### Adding Alt Text Attribute to Media Record Source: https://laravel-mediable.readthedocs.io/en/latest/uploader Demonstrates how to associate alt text with the media record during the upload process using the `withAltAttribute()` method. This is crucial for accessibility and SEO purposes. ```php withAltAttribute(‘This is the alt text’) ->upload(); ``` -------------------------------- ### Checking for Media Presence Source: https://laravel-mediable.readthedocs.io/en/latest/mediable Shows how to check if a model has media attached to specific tags using `hasMedia()`. It also demonstrates how to query for models that have media attached using `whereHasMedia()`. ```php hasMedia('thumbnail')){ // ... } $posts = Post::whereHasMedia('thumbnail')->get(); ``` -------------------------------- ### Query Media by Aggregate Type (PHP) Source: https://laravel-mediable.readthedocs.io/en/latest/types This snippet demonstrates how to query for all media items belonging to a specific aggregate type, such as images. It utilizes the Media model and its predefined aggregate type constants. No external dependencies are required beyond the Laravel-Mediable package. ```php get(); ``` -------------------------------- ### Configure Intervention/image Manager (<3.0) Source: https://laravel-mediable.readthedocs.io/en/latest/variants Manually binds the ImageManager class to the service container, specifying the driver (imagick or gd). This is an alternative to using the intervention/image Laravel service provider. ```php app->bind( ImageManager::class, function() { return new ImageManager(['driver' => 'imagick']); // return new ImageManager(['driver' => 'gd']); } ); } } ``` -------------------------------- ### Configure Media Upload Validation Rules Source: https://laravel-mediable.readthedocs.io/en/latest/configuration This PHP snippet illustrates validation configuration options within `config/mediable.php` for media uploads. It covers maximum file size, handling of duplicate files, strict type checking, allowing unrecognized types, and specifying allowed MIME types, extensions, and aggregate types. ```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\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' => [], //... ``` -------------------------------- ### Manipulate Images During Upload - PHP Source: https://laravel-mediable.readthedocs.io/en/latest/uploader Illustrates how to perform image manipulations during the upload process using the Intervention Image library. It defines a manipulation callback to resize an image and then applies it to the uploaded file. This process occurs synchronously and overwrites the original file. An alternative using a registered variant name is also shown. ```php fit(100, 100); })->outputPngFormat(); $media = MediaUploader::fromSource($request->file('image')) ->applyImageManipulation($manipulation); ->upload() // alternatively you can reference a register variant name $media = MediaUploader::fromSource($request->file('image')) ->applyImageManipulation('thumbnail') ->upload() ``` -------------------------------- ### Import String File Data to Media - PHP Source: https://laravel-mediable.readthedocs.io/en/latest/uploader This method enables the import of file data directly from a string, such as encoded image data. The `fromString` method takes the file content as a string and allows for subsequent configuration of its destination before uploading. ```PHP encode('jpg'); MediaUploader::fromString($jpg) ->toDestination(...) ->upload(); ``` -------------------------------- ### Handling Duplicate Files during Upload Source: https://laravel-mediable.readthedocs.io/en/latest/uploader Details the different strategies for handling cases where a file with the same name already exists at the destination. Options include incrementing the filename, replacing the existing file and record, or throwing an error. These methods provide control over data integrity and overwrite policies. ```php onDuplicateIncrement(); // Replace old file and update Media record $uploader->onDuplicateUpdate(); // Replace old file and Media record, break associations $uploader->onDuplicateReplace(); // Replace old file and Media record, break associations, delete variants $uploader->onDuplicateReplaceWithVariants(); // Cancel upload and throw an exception $uploader->onDuplicateError(); ``` -------------------------------- ### Eloquent Model with Mediable Trait Source: https://laravel-mediable.readthedocs.io/en/latest/mediable This snippet shows how to add the `Mediable` trait and `MediableInterface` to an Eloquent model to enable media attachment capabilities. It requires the `PlankMediable` package. ```php makeVariantOf($otherMedia, 'small')->save(); $media->makeVariantOf($otherMediaId, 'small')->save(); ``` -------------------------------- ### Disabling Media Order with unordered() Source: https://laravel-mediable.readthedocs.io/en/latest/mediable Demonstrates how to disable the default ordering of media in queries using the `unordered()` scope on the `media()` relationship. This is useful when order is not relevant. ```php media() ->unordered() ->... ``` -------------------------------- ### Promote Variant to Original Source: https://laravel-mediable.readthedocs.io/en/latest/variants Manually change a variant media record to become the original media record. This action clears the variant name and detaches it from its previous variant family. ```php makeOriginal()->save(); ``` -------------------------------- ### Handle Media Upload Exceptions in Handler - PHP Source: https://laravel-mediable.readthedocs.io/en/latest/uploader This snippet demonstrates how to use the HandlesMediaUploadExceptions trait within an application's exception handler to transform media upload exceptions into more granular HTTP exceptions. This allows for specific HTTP status codes to be returned based on the nature of the upload error, such as '413 Request Entity Too Large'. ```PHP transformMediaUploadException($e); return parent::render($request, $e); } } ``` -------------------------------- ### Manage File Visibility for Image Variants in Laravel Mediable Source: https://laravel-mediable.readthedocs.io/en/latest/variants Provides methods to control the filesystem visibility of newly created image variants. Options include setting them to private, public, or matching the visibility of the original media file. ```php makePrivate(); $manipulation->makePublic(); // to copy the visibility of the original media file $manipulation->matchOriginalVisibility(); ``` -------------------------------- ### Deleting Media Records and Files - PHP Source: https://laravel-mediable.readthedocs.io/en/latest/media Details how to delete a Media record and its associated file using the standard Eloquent `delete()` method. It also highlights that deleting via the query builder will not remove the file from the disk. ```php delete(); // Note: Deleting via the query builder does NOT delete the file. // Media::where(...)->delete(); // This will not delete files ``` -------------------------------- ### Define Image Variants with Manipulations Source: https://laravel-mediable.readthedocs.io/en/latest/variants Defines image variants ('thumb', 'bw-square') using ImageManipulator. Each variant includes a callback to modify the image (e.g., fit, greyscale) and can specify output formats. ```php fit(32, 32); })->outputPngFormat() ); ImageManipulator::defineVariant( 'bw-square', ImageManipulation::make(function (Image $image, Media $originalMedia) { $image->fit(128, 128)->greyscale(); }) ); } } ``` -------------------------------- ### Replace Media File - PHP Source: https://laravel-mediable.readthedocs.io/en/latest/uploader The `replace()` method allows you to substitute the file associated with an existing `Media` record. This operation uploads a new file and updates the current media record, ensuring that any existing attachments to other models remain intact. ```PHP replace($media); ``` -------------------------------- ### Check Media Type (Original vs. Variant) Source: https://laravel-mediable.readthedocs.io/en/latest/variants Determine if a Media object is an original upload or a derivative variant. You can also check for specific variant names. ```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 ``` -------------------------------- ### Handling Soft Deletes for Media - PHP Source: https://laravel-mediable.readthedocs.io/en/latest/media Explains how to configure soft deletes for Media records. If `forceDelete()` is used on a subclass with the `SoftDeletes` trait, the associated file is deleted. Configuration options for detaching relationships on soft delete are also mentioned. ```php forceDelete(); // Deletes file and detaches relationships // Configuration in config/mediable.php: // 'detach_on_soft_delete' => true // Automatically detach relationships on soft delete ``` -------------------------------- ### Alter Media Model Before Saving - PHP Source: https://laravel-mediable.readthedocs.io/en/latest/uploader Demonstrates how to modify the `PlankMediableMedia` model instance before it is saved to the database. This is achieved by passing a callable to the `beforeSave` method, which receives the model and the source adapter as arguments, allowing custom attributes or logic to be applied. ```php file('image')) // model class to use ->setModelClass(CustomMediaClass::class) // pass the callable ->beforeSave(function (Media $model, SourceAdapterInterface $source) { $model->setAttribute('customAttribute', 'value') }) ->upload() ``` -------------------------------- ### Set File Visibility (Public/Private) - PHP Source: https://laravel-mediable.readthedocs.io/en/latest/uploader Explains how to control the public accessibility of an uploaded file on a per-file basis. The `makePrivate()` method disables public access, while `makePublic()` (the default behavior) allows it. These methods can be chained with other upload configurations. ```php file('image')) ->makePrivate() // Disable public access ->makePublic() // Default behaviour ->upload() ``` -------------------------------- ### Configure Database Connection in Laravel-Mediable Source: https://laravel-mediable.readthedocs.io/en/latest/configuration This configuration option allows you to specify the database connection name that Laravel-Mediable will use. If set to null, the package will default to using Laravel's default database connection. ```php null, //... ``` -------------------------------- ### Customize Image Variant Output Destination in Laravel Mediable Source: https://laravel-mediable.readthedocs.io/en/latest/variants Explains how to customize the output location for generated image variants. You can specify the disk, directory, and filename, or use hashing for unique filenames. The library handles duplicate filenames by default via incrementing, but can be configured to throw an error. ```php toDisk('uploads'); $manipulation->toDirectory('files/variants'); // shorthand for the above $manipulation->toDestination('uploads', 'files/variants'); $manipulation->useFilename('my-custom-filename'); $manipulation->useHashForFilename(); // defaults to md5 $manipulation->useHashForFilename('sha1'); $manipulation->useOriginalFilename(); //restore default behaviour $manipulation->onDuplicateIncrement(); // default behaviour $manipulation->onDuplicateError(); ``` -------------------------------- ### Configure Custom Medibles Table Name Source: https://laravel-mediable.readthedocs.io/en/latest/mediable Allows you to specify a custom name for the joining table used for media-to-mediables relationships. Modify the `mediables_table` key in `config/mediable.php`. ```php /* * Name to be used for mediables joining table */ 'mediables_table' => 'prefixed_mediables', ``` -------------------------------- ### Prune Missing Media Files with Artisan Source: https://laravel-mediable.readthedocs.io/en/latest/commands Deletes media records from the database that correspond to files no longer present on the disk. This helps maintain data integrity by removing orphaned records. It accepts an optional disk name argument. ```bash $ php artisan media:prune [disk] ``` -------------------------------- ### Define and Generate Tagged Image Variants Source: https://laravel-mediable.readthedocs.io/en/latest/variants Define image variants with tags for grouping and then generate all variants associated with a specific tag. This allows for organized management and batch generation of related variants. ```php