How to get and delete files from storage using Laravel? - laravel

I'm building a job search application where a Candidate User can upload a profile of themselves along with 3 (quick, about 30 second) videos based on pre determined questions. For example one of the questions is "1. What makes you stand out over other candidates?". He can video himself answering the question and then upload the video.
The way my system works is, the videos get uploaded to a tmp Disk that I created and into a videos folder, then the files get uploaded to s3.
After this happens I want to delete the files from the tmp folder but I keep getting errors.
Here is the tmp Disk in config/filesystems.php:
'tmp' => [
'driver' => 'local',
'root' => storage_path(),
'url' => env('APP_URL').'/storage',
'visibility' => 'public'
],
I think that there might be a bug in my application because I can't delete any files from this location, in fact I can't even get them.
When I try to get a file and die dump it that I know is in storage/videos/ folder like this:
dd(Storage::get(storage_path().'/videos/1607107892Pexels-Videos-1181911-copy.mp4'));
When I click on the network tab on the response it says No response data.
and if I try to delete a file like this:
Storage::delete(storage_path().'/videos/1607107892Pexels-Videos-1181911-copy.mp4'));
I keep getting this error:
League\Flysystem\FileNotFoundException: File not found at path: videos/1607107892Pexels-Videos-1181911-copy.mp4 in /Applications/XAMPP/xamppfiles/htdocs/highrjobsadminlte/vendor/league/flysystem/src/Filesystem.php:389
What am I doing wrong?

Get file using storage facade
You can specify the disk using the Storage facade and then get your desired files. Something like below code may help you:
Storage::disk('tmp')->get('videos/1607107892Pexels-Videos-1181911-copy.mp4')
Delete file using facade
As said in getting file section, you can delete any file or directory after specifying the disk.
Storage::disk('tmp')->delete('videos/1607107892Pexels-Videos-1181911-copy.mp4')
Check available directories and files
If you doubt about whether you're in the correct disk or not, you can check the existing directories and files in the target disk using allDirectories() or allFiles() methods.
Storage::disk('tmp')->allDirectories();
Storage::disk('tmp')->allFiles();

The default disk used by filesystem is configured in config/filesystems.php
'default' => env('FILESYSTEM_DRIVER', 'local'),
'disks' => [
//other disks
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
//...
]
However you use a custom disk tmp when storing the file and have set it's root to storage_path() whereas the default local disk has the root path set to storage_path('app')
So inorder to delete the file in tmp disk you should specify the disk
Storage::disk('tmp')->delete('/videos/1607107892Pexels-Videos-1181911-copy.mp4');

Related

Laravel: upload folder is created in the wrong directory

I have a form with a file input ready to be saved.
$request->validate([
'name'=> 'required|min:3',
'image'=> 'required|image|mimes:jpeg,png,jpg'
]);
$category = new Category();
$category->name = $request->name;
$path = $request->file('image')->store('categories_images');
$category->image = $path;
What the above code does is that it grabs the image field from the request and save it to the categories_images folder. When I first uploaded a file to test it it created the folder in storage/app.
My problem is that I want to preview the images on my site:
//store.state.serverPath returns: http://localhost:8000 -> this is right
<img :src="`${$store.state.serverPath}/storage/${category.image}`" class="image-wd"/>
When I inspect it in the nrowser it says:
http://localhost:8000/storage/categories_images/adGR57Gq6lNUqRVvEubRDfxNMZzEhya3A7oESUox.png not found
It expects the images in storage/app/public but creates the categories_images folder everytime I upload an image in storage/app. Am I missing something here?
It seems I can't post a comment just as an answer. So let me add my input. Did you create your symbolic link? If not do it now, or just redo it. I had the same issue when i ported my code from mac to windows. Even if all the configuration was done corectly the link was related to my mac. I just fixed that issue now for my code. So thank you for your question.
php artisan storage:link
Also the first parameter of store is the path you want to save the file under storage/public directory. You need to append the directory name in yor url to find the file.
This is the code I use in one of my projects.
$path = isset($validated['document']) ? $path = $request->file('document')->store('pdfs', 'public') : null;
The file will be accessed with the url www.example.com/storage/pdfs/$path
document is the name of file input.
You miss the part of the tutorial where he changed the config -> filesystems.php with this
'local' => [
'driver' => 'local',
'root' => storage_path('app/public'),
],

Deleting file with Laravel

i'm having troble deleting a file from a Laravel Project.
The file is in the /storage/exports directory, it's an excel stored on the disk usingthe Laravel Excel library.
This is my code:
$path = $excel->store('xls', false, true)['full'];
...send the xls via mail....
Storage::delete($path);
When i check the existence of the file with file_exist i get true, so Laravel is able to read the file.
I've also checked the permission for the folder and i give all permissions on this folder using chmod 777
Any ideas?
Thanks!
The storage driver already has an awareness of a root directory, so the $path must be relative, not full. So if your file is in:
/this/is/the/full/path.xls, and the config filesystems.disks.local.root is set to /this/is/the/full, you're essentially having it look for a file in /this/is/the/full/this/is/the/full/path.xls.
You have two options.
1) Add a new driver to that config, and reference it directly:
'custom_location' => [
'driver' => 'local',
'root' => '/some/other/root/path',
]
Storage::driver('custom_location')->delete($relativePathFromRoot)
2) Create a one-off:
$rootPath = '/some/other/root/path';
$client = Storage::createLocalDriver(['root' => $rootPath]);
$client->delete($relativePathFromRoot);
Try storing the file within storage/app/exports. The Storage class's default location to store files is storage/app.
It may be a good idea to instead of using the Excel class to store the file, to instead save the file using the Storage class: Storage::put('exports/excelfile.xls', $fileContents);
Even though you are using Laravel, you can use regular PHP functions.
unlink($path);

Adding Email Attachments From Local Storage

I am using laravel/lumen. I am able to save files using Storage::disk("local")->put(); in my storage directory. However now I want to attach a few of those files to an email and send, this is done with a job the error I get is
lumen.ERROR: exception 'Swift_IoException' with message 'Unable to
open file for reading
Now I read something about symbolic linking which I tried but that simply did not change the result, I was still unable to attach files i n my storage folder to my emails.
This is my directory structure:
/home/xxxxxx/:
-example.app
--storage
---app
----public
-public_html
--example.app
---storage
Attaching the file like this:
foreach ($params["attachments"] as $attachment) {
$mail->attach($attachment["file"], [
'as' => $attachment["name"],
'mime' => $attachment["mime"]
]);
}
You've already realized that attach() method expects the full path to the file. However, others may find useful know how to achieve that. So, in case you're using the default settings for local store, you may be able to get the full path by calling the storage_path() helper. This way:
/*
* This will return the full path to the file:
*
* /path/to/laravel/storage/app/attachment/path
*/
storage_path('app/' . $attachment['file']);
Okay so apparently swift mailer fails when you pass a full url instead of the real path to the file. Didn't know this, don't know if it's a bug or it was done by design.

Puppet - How do I move the contents of a directory to another existing directory?

I have a directory full of .data files and .config/.config.example files. I need to move all of the .data files to a different existing directory on my system using puppet. The puppet code I currently have is incorrect I believe - what am I doing wrong?
file { 'Owasp .data files':
ensure => directory,
path => '/etc/nginx/',
source => '/usr/src/SpiderLabs-owasp-modsecurity-crs-0475e92/',
recurse => true,
ignore => ['*.conf', '*.conf.example'],
}
I was hoping this would copy everything except for the .conf and .conf.example files to /etc/nginx. However, I get the following error:
box: Error: Cannot alias File[Owasp .data files] to ["/etc/nginx"] at /vagrant/modules/nginx_test/manifests/test.pp:112; resource ["File", "/etc/nginx"] already declared at /usr/share/puppet/modules/nginx/manifests/config.pp:193
So your problem is actually that you have a file { '/etc/nginx': } declared somewhere else in your catalog. You need to only declare that resource once per catalog. That will fix your error. You also cannot declare two file resources with different titles that both have the same path parameter as Puppet tests that parameter for resource uniqueness.
Regarding your specific question though, you would use the file URI in the source parameter: https://docs.puppet.com/puppet/latest/reference/type.html#file-attribute-source
So for your situation, you would do:
file { 'Owasp .data files':
ensure => directory,
path => '/etc/nginx/',
source => 'file:///usr/src/SpiderLabs-owasp-modsecurity-crs-0475e92/',
recurse => true,
ignore => ['*.conf', '*.conf.example'],
}

How to use a Puppet File Resource to give different permissions on a directory than to it's files?

I would like to use Puppet to manage a directory. I want the directory to be owned by user root and group admin, with 0770 permissions.
I would like all files in the directory to be owned by user apache and group admin with 0600 permissions.
I have yet to find a way to achieve this using the file resource in Puppet. I have tried using two resources like so:
file { 'phpsessions_files':
path => '/var/phpsessions',
ensure => directory,
owner => 'apache',
group => 'admin',
mode => 0600,
recurse => true,
before => File['phpsessions_dir'],
}
file { 'phpsessions_dir':
path => '/var/phpsessions',
recurse => false,
owner => 'root',
group => 'admin',
mode => 0770,
}
But I am not allowed to create two file resources to the same path and I can't see how to achieve what I want with just one resource.
Your help is much appreciated.
Create a define containing an exec to change the mode of the directory after it is recursed.
http://projects.puppetlabs.com/projects/1/wiki/File_Permission_Check_Patterns
To the best of my knowledge this is not possible in puppet. i would manage only the following
file { 'phpsessions_dir':
path => '/var/phpsessions',
recurse => false,
owner => 'root',
group => 'admin',
mode => 0770,
}
php/apache should create the files within this folder with the correct permissions, If they don't fix that in php.ini. If you are worried that something else is gonna come along and change the permissions then fall back to a cron job or better yet a systemd.timer to periodicity check and correct them

Resources