PHP code example of aniftyco / laravel-attachments

1. Go to this page and download the library: Download aniftyco/laravel-attachments library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

aniftyco / laravel-attachments example snippets


use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();

            // Single attachment
            $table->attachment('avatar');

            // Multiple attachments
            $table->attachments('photos');

            $table->timestamps();
        });
    }
};

use NiftyCo\Attachments\Casts\AsAttachment;

class User extends Model
{
    protected function casts(): array
    {
        return [
            'avatar' => AsAttachment::class,
        ];
    }
}

use NiftyCo\Attachments\Attachment;

class UserController
{
    public function store(UserStoreRequest $request, User $user)
    {
        $user->avatar = Attachment::fromFile($request->file('avatar'), folder: 'avatars');

        $user->save();

        // ...
    }
}

use NiftyCo\Attachments\Casts\AsAttachments;

class Post extends Model
{
    protected function casts(): array
    {
        return [
            'images' => AsAttachments::class,
        ];
    }
}

use NiftyCo\Attachments\Attachments;

class PostController
{
    public function store(PostStoreRequest $request, Post $post)
    {
        // Create from multiple files at once
        $post->images = Attachments::fromFiles($request->file('images'), folder: 'posts');

        // Or add files one at a time
        foreach ($request->file('images') as $image) {
            $post->images->attach($image, folder: 'posts');
        }

        $post->save();
    }
}

$attachment = $user->avatar;

$attachment->name();      // File name
$attachment->disk();      // Storage disk name
$attachment->folder();    // Folder path
$attachment->path();      // Full path (folder/name) - alias for name()
$attachment->size();      // File size in bytes
$attachment->mimeType();  // MIME type
$attachment->extname();   // File extension (e.g., 'jpg')
$attachment->extension(); // Alias for extname()
$attachment->url();       // Public URL

// Public URL (for public disks)
$url = $user->avatar->url();

// Temporary URL (for private disks)
$url = $user->avatar->temporaryUrl(now()->addHours(1));

// Or use minutes
$url = $user->avatar->temporaryUrl(60); // 60 minutes

// Check if file exists
if ($user->avatar->exists()) {
    // File exists
}

// Get file contents
$contents = $user->avatar->contents();

// Download file
return $user->avatar->download();
return $user->avatar->download('custom-filename.jpg');

// Get human-readable file size
$size = $user->avatar->readableSize(); // "1.5 MB"

// Delete attachment
$user->avatar->delete();

// Count attachments
$count = $post->images->count();

// Loop through attachments
foreach ($post->images as $image) {
    echo $image->url();
}

// Add a new attachment
$post->images->attach($file, folder: 'posts');

// Remove an attachment
$post->images = $post->images->filter(fn($img) => $img->name() !== 'old.jpg');
$post->save();

use NiftyCo\Attachments\Concerns\HasAttachmentCleanup;

class User extends Model
{
    use HasAttachmentCleanup;

    protected function casts(): array
    {
        return [
            'avatar' => AsAttachment::class,
        ];
    }
}

$user->delete(); // Avatar file is automatically deleted from storage

// Old avatar file is automatically deleted when replaced
$user->avatar = Attachment::fromFile($newFile, folder: 'avatars');
$user->save();

// config/attachments.php

return [
    // Disable cleanup when models are deleted
    'auto_cleanup' => false,

    // Disable cleanup when attachments are replaced
    'delete_on_replace' => false,
];

return [
    /*
    |--------------------------------------------------------------------------
    | Default Disk
    |--------------------------------------------------------------------------
    |
    | The default filesystem disk to use for storing attachments.
    | This should match one of the disks defined in config/filesystems.php
    |
    */
    'disk' => env('ATTACHMENTS_DISK', 'public'),

    /*
    |--------------------------------------------------------------------------
    | Default Folder
    |--------------------------------------------------------------------------
    |
    | The default folder path where attachments will be stored.
    | You can override this per-attachment when creating them.
    |
    */
    'folder' => env('ATTACHMENTS_FOLDER', 'attachments'),

    /*
    |--------------------------------------------------------------------------
    | Automatic Cleanup
    |--------------------------------------------------------------------------
    |
    | When enabled, attachment files will be automatically deleted from storage
    | when the parent model is deleted. Requires the HasAttachmentCleanup trait.
    |
    */
    'auto_cleanup' => env('ATTACHMENTS_AUTO_CLEANUP', true),

    /*
    |--------------------------------------------------------------------------
    | Delete on Replace
    |--------------------------------------------------------------------------
    |
    | When enabled, the old attachment file will be automatically deleted
    | when it's replaced with a new attachment.
    |
    */
    'delete_on_replace' => env('ATTACHMENTS_DELETE_ON_REPLACE', true),

    /*
    |--------------------------------------------------------------------------
    | Temporary URL Expiration
    |--------------------------------------------------------------------------
    |
    | The default expiration time (in minutes) for temporary URLs.
    | This is used when calling temporaryUrl() without an expiration parameter.
    |
    */
    'temporary_url_expiration' => env('ATTACHMENTS_TEMP_URL_EXPIRATION', 60),
];
sh
php artisan vendor:publish --tag=attachments-config
sh
php artisan vendor:publish --tag=attachments-config