gurgentil / laravel-storable

A Laravel package to create storage transformers for your models.

Stars
0

Laravel Storable

Latest Version
GitHub Workflow Status
Quality Score
MIT Licensed

Create storage transformers for your Eloquent models.

Installation

Install the package via composer:

composer require gurgentil/laravel-storable

Usage

Create a storable class:

php artisan make:storable StorableUser

Define the file path and the object representation you want to store:

<?php

namespace App\Storables;

use App\Models\User;
use Gurgentil\LaravelStorable\Storable;

class StorableUser extends Storable
{
    /**
     * @var User
     */
    protected $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * Get file path in storage.
     *
     * @return string
     */
    public function getFilePath(): string
    {
        return "users/{$this->user->uuid}.json";
    }

    /**
     * Get string representation of object to store.
     *
     * @return string
     */
    public function getContents(): string
    {
        return json_encode([
            'id' => $this->user->id,
            'email' => $this->user->email,
            'permissions' => $this->user->permissions->pluck('name')->toArray(),
        ]);
    }
}

To write the object to storage, simply call save() on the object:

$storable = new StorableUser($user);
$storable->save();

Call delete() to remove the file from storage:

$storable = new StorableUser($user);
$storable->delete();

You can define the disk via environment variable or by passing it to the save and delete methods:

STORABLE_DISK=gcs
$storable = new StorableUser($user);
$storable->save('gcs');

Testing

composer test

Changelog

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

Contributing

Please see CONTRIBUTING for details.

Credits

License

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