I have stored a .csv file in this directory in Laravel 5 :
/storage/app/data.csv
Inside of this function I am trying to read the contents of this file and extract a few columns from it, like name and city to an array, sample code:
use Illuminate\Support\Facades\Storage;
public function get_data() {
$file_n = Storage::url('data.csv');
$file = fopen($file_n, "r");
$all_data = array();
while ( ($data = fgetcsv($file, 200, ",")) !==FALSE {
$name = $data[0];
$city = $data[1];
$all_data = $name. " ".$city;
array_push($array, $all_data);
}
fclose($file);
}
I am getting an ErrorException in Controller:
fopen(/storage/data.csv): failed to open stream: No such file or directory
But the file is there. Is there a better way to do this instead?
Thanks for looking!
Your issue is with the path as previous people pointed out.
You can use the helper function storage_path
https://laravel.com/docs/5.3/helpers#method-storage-path
In your case it will be used like this:
storage_path('app/data.csv');
As a recomendation you can use this libary to work with CSV/Excel files, it's pretty easy to use: https://github.com/Maatwebsite/Laravel-Excel
Laravel 5.7
try this :
Storage::disk('local')->path('import.csv');
It should be good.
I figured it out by using "storage_path".
...
$filename = storage_path('/app/data.csv');
$file = fopen($filename, "r");
$all_data = array();
while ( ($data = fgetcsv($file, 200, ",")) !==FALSE ) {
...
}
Thanks!
I solved this issue by adding a url key to my local disk config in config/filesystems.php like so:
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
'url' => storage_path('app')
],
Now I can reference Storage::url('filename.txt') and it returns:
/home/josh/apps/storage/app/filename.txt
Try the below
$file_n = Storage::get('data.csv');