devfelipereis/uploadtrait

A simple upload trait for Laravel

dev-master 2019-01-16 13:31 UTC

This package is not auto-updated.

Last update: 2024-05-17 01:24:31 UTC


README

A simple upload trait for laravel. It will upload to the local storage if in development and to a s3 bucket if in production/staging.

For production, you need to follow the laravel documentation to set s3 as your default cloud disk.

Just tested with Laravel 5.4+. But it should work with Laravel 5.x.

Note: This is something made for my setup and works good. I like storage for dev and s3 for production. Feel free to change whatever you like to meet your needs ;)

When not using s3, the generated url will be something like this: site.com/storage?path=something/something.jpg
Do not use this in production, it's only for dev.
It is vulnerable with Full Path Disclosure (https://www.owasp.org/index.php/Full_Path_Disclosure)

How to install

composer require devfelipereis/uploadtrait:dev-master

If you are running Laravel 5.4 or below, you will need to add the service provider to the providers array in your app.php config as follows:

DevFelipeReis\UploadTrait\UploadTraitServiceProvider::class

Now see the example below to understand how to use it.

Example

In your model, set the base path for your uploads:

...
use DevFelipeReis\UploadTrait\UploadTrait;

class Company extends Model
{
    use UploadTrait;

    ...

    public function getBaseUploadFolderPath() {
        return 'companies/' . $this->id . '/';
    }
}

Now in your controller...

public function store(CreateCompanyRequest $request)
{
    ...
    $inputs = $request->except('logo');
    $company = $this->companyRepository->create($inputs);

    // Company logo
    $company_logo = $request->file('logo');
    if ($company_logo) {
        $company->logo = $company->uploadFile($company_logo);
        // $company->logo will be something like: companies/1/8e5dc57cb5d80532f52e13597c5f0b68.jpg
    }

    $company->save();

    ...
}

How to access the image?

Finally, inside the view:

...
<img id="logo-img" class="thumbnail preview-img" src="{{ $company->getUploadUrlFor('logo') }}"/>
...

How to delete the image?

Maybe you want to delete that image, try this:

$company->deleteUploadFor('photo');