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)
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.
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();
...
}
Finally, inside the view:
...
<img id="logo-img" class="thumbnail preview-img" src="{{ $company->getUploadUrlFor('logo') }}"/>
...
Maybe you want to delete that image, try this:
$company->deleteUploadFor('photo');