mohammedmanssour/file-cast

Easily manage uploaded files in your Laravel app, with automatic path saving and handy value objects for effortless access.

v0.3.1 2024-05-19 15:27 UTC

This package is auto-updated.

Last update: 2024-12-19 16:49:51 UTC


README

Latest Version on Packagist GitHub Code Style Action Status Total Downloads

This Laravel package makes file management straightforward. It automatically saves uploaded files to the disk and stores their paths in the database. When you retrieve these files, it wraps the paths in easy-to-use value objects. The package also keeps track of any changes, ensuring old files are deleted when updates occur. It’s a simple way to keep your file handling neat and efficient.

Features

  • Mapping uploaded files from the Request to the Model.
  • Old files are automatically deleted upon model update or deletion.
  • File Value Object for easy access

Installation

You can install the package via composer:

composer require mohammedmanssour/file-cast

You can publish the config file with:

php artisan vendor:publish --tag="file-cast-config"

Usage

  1. Add the FileCast to your casts list
protected $casts = [
    'government_id' => FileCast::class, // uses table name as storage path, public visibility and the configured default disk
    'verification_video' => FileCast::class.':verification', // uses verification as storage path, public visisbility and the configured default disk
    'profile_picture' => FileCast::class.':pics,,s3', // uses pics as storage path, and s3 as storage disk
];
  1. Optional, if you want to clean old files upon model update or delete, add the following observer to your model
User::observe(UploadedFilesObserver::class);
  1. On Model Retrieval, the casted attribute is converted to a file object that provides the following method
$model->profile_picture->path(); // return the saved path in the db.
$model->profile_picture->fullPath(); // return the full path based on the provided disk
$model->profile_picture->size(); // return the file size
$model->profile_picture->url(); // return the file url based on the provided disk
$model->profile_picture->exists(); // return true of false
$model->profile_picture->delete(); // delete the file

Testing

composer test

Changelog

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

Credits

License

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