Laravel 5.3 import CSV from file without uploading - laravel

I am using Maatwebsite/Excel to import CSV files. My code looks like this tutorial: http://itsolutionstuff.com/post/laravel-5-import-export-to-excel-and-csv-using-maatwebsite-exampleexample.html
I marged both functions and my script gets file and returns file/
But despite many attempts I can't skip uploading file. It means, that I have CSV file in special folder, and I would like to get this file to process data, without uploading. It will automatically get file (maybe file_get_contents ?), and pass it to Illuminate\Support\Facades\Input.

This is the perfect way to import your csv in laravel 5.*
public function importExcel() {
if (Input::hasFile('import_file')) {
$path = Input::file('import_file')->getRealPath();
$data = Excel::load($path, function($reader) {
})->get();
if (!empty($data) && $data->count()) {
$count = 0;
foreach ($data as $key => $d) {
$insert = array();
$insert['name'] = $value->name;
$this->user->create($insert);
}
}
}
}

You can read your excel file using this code
// for sheet 1
$excelData = $excel->selectSheetsByIndex(0)->load($yourFilePath)->get();
print_r($excelData);

I found solution. We can skip if (Input::hasFile('import_file')) { and $path variable set to our CSV file path

Related

Sort storage files by modified date in Laravel

I'm building a personal blog using Laravel 8, where the articles are displayed from .md files (no database). Everything works perfectly, but I'm struggling to sort those .md files by the modified date or creation date. Files are placed into the storage folder
Current code:
// Getting files from storage:
$files = Storage::disk('articles')->allFiles();
$articles = [];
foreach ($files as $file) {
$storage = Storage::disk('articles')->get($file);
array_push($articles, $storage);
$collection = collect($articles);
}
$array = collect($articles);
$articles = $this->paginate($array);
return view('pages.home', compact('articles'));
I've tried to get file details using the filemtime() function, but I get the following error:
$filePath = Storage::path($file);
$fileDate = filemtime($filePath);
dd($fileDate);
ErrorException
filemtime(): stat failed for C:\my-project\storage\app\article-file.md
stat function returns the same error.
Storage is linked, file exists, it returns the right path...
I'm out of ideas...
Laravel already has method to read last modify file metadata
Storage::lastModified($name);
Link to documantation:
https://laravel.com/docs/8.x/filesystem#file-metadata

How can I set encoding for export csv with Laravel Excel in Laravel

I using Laravel Excel for export CSV file in Laravel.
How can I set the encoding for export csv file.
I have tried several ways:
Change config in excel.php
'use_bom' => false,
Use mb_convert_encoding to convert content to before export.
$exportData = mb_convert_encoding($exportData, "SJIS", "UTF-8");
$pblClassExport = new \App\Exports\PblClassExport($exportData, 'test.csv');
But it's not working. The encoding of csv file auto change by file content.
you need to configure your PblClassExport.php headers
in PblClassExport.php
/**
* Optional headers
*/
private $headers = [
'Content-Type' => 'text/csv',
'Content-Encoding'=> 'SHIFT-JIS' // somthing like this ?
];
i have't done this but i think it will work
ref link
https://docs.laravel-excel.com/3.1/exports/exportables.html#exportables
Update
you can encode line by line
public function bindValue(Cell $cell, $value)
{
$value = mb_convert_encoding($value, "SJIS");
return parent::bindValue($cell, $value);
}
ref link https://www.gitmemory.com/issue/Maatwebsite/Laravel-Excel/1886/552849170
If you you use Laravel Excel 3.1, you can use WithCustomCsvSettings interface. Then you add your encoding setting in the getCsvSettings method like the following.
use Maatwebsite\Excel\Concerns\WithCustomCsvSettings;
class InvoicesExport implements WithCustomCsvSettings
{
public function getCsvSettings(): array
{
return [
'output_encoding' => 'SJIS',
];
}
}
Plese refer to the docs for more details.
I resolved it. Let's me share my solution here.
Laravel Excel not support it by default.But we can do it by simple way.
Get csv content before download: \Excel::raw
Convert to another encoding: mb_convert_encoding
https://docs.laravel-excel.com/3.1/exports/collection.html#storing-raw-contents
Download csv.
$exportedObject= new \App\Exports\ClassExport($exportDataArray, $fileName);
$csvContent = \Excel::raw($exportedObject, $exportedObject->writerType);
$csvContent = mb_convert_encoding($csvContent, 'SJIS', 'auto');
// In my case, I upload my csv to S3.
$storageInstance = \Storage::disk('s3_import_csvs');
$putFileOnStorage = $storageInstance->put($fileName, $csvContent);
Note: Solution povided by OP on question section.

download file as unknown file in laravel

I want to download a pdf file from storage
public function show($free)
{
$dl = SingleFreeDownload::find($free);
return Storage::download($dl->file , $dl->title);
}
and this is the file storage code:
public function store(Request $request)
{
$file = $request->file('file')->store('uploads');
$single_download_page=[
'file' => $file, ];
SingleFreeDownload::create($single_download_page);
}
when I click on download button it downloads unknown file and it not open what is the problem?
First I wouldn't call the method which shall download a file show() I would rename it to download. Second I would check whether the file exists or not if it exists I would try to download it.
You can check whether it exists or not using this:
$exists = Storage::exists('myfile.jpg');
if ($exists) {
return Storage::download($dl->file , $dl->title);
}
Furthermore you should check wether your input contains the name file since you are doing this:
$file = $request->file('file')->store('uploads');
Your input needs to look like this:
<input name="file"...>
You should also show what this class does SingleFreeDownload.

Laravel import Excel how to select a sheet from excel file and import it to database table

I'm using Laravel 5.2 and I'm trying to import an excel file to my database using Laravel excel package.
the file contains many sheets, I want to import every sheet to a different table in the database.
I have tried the following code but I couldn't find any result.
$file = Input::file('file');
$file_name = $file->getClientOriginalName();
Excel::selectSheets('Branches')->load($file, function($reader){
$reader->each(function($sheet){
foreach($sheet->toArray() as $row){
Branch::firstOrCreate($row=$sheet->toArray());
echo'done';
dd($row);
}
});
});
After trying, searching and going through Laravel Excel documentation, I found that I have to load the whole Excel file and inside this process I can use the sheets selection methods which is given by the package.
Example:
foreach($getSheetName as $sheetName)
{
if ($sheetName === 'Branches')
{
Excel::selectSheets($sheetName)->load($request->file('file'), function ($reader)
{
foreach($reader->toArray() as $sheet)
{
Branch::create($sheet);
}
});
}
}

How to display file which had already upload laravel 5.2?

I upload file in to my database and moved that file as same name in documents folder in a root path like below :)
public function store(PslCall $call,Request $request)
{
$this->validate($request, $this->rules);
$uploadDestinationPath = base_path() . '/documents/';
$current_id = Document::where('call_id',$call->id)->count()+1;
if ($request->hasFile('file'))
{
$file =$request->file;
$fileName = $file->getClientOriginalName();
$file->move($uploadDestinationPath, $call->id.'_'.$current_id.'_'.$fileName);
}
$input = $request->all();
$input['file'] = $call->id.'_'.$current_id.'_'.$fileName;
$input['call_id'] = $call->id;
Auth::user()->documents()->create($input);
return Redirect::route('calls.documents.index',$call->id)->with('message','You have successfully submitted');
}
its works perfect now im display in my index page all the files like below :)
<td>{{strtoupper($document->title)}}</td>
<td>{{$document->file}}</td>
now my route file i have route to display my file like this :
Route::get('documents/{file}',function() {
return 'hi';
});
here im getting hi output when i click <td>{{$document->file}}</td> this path
but i want know how to display file which i upload same file name ?
As documentation says if you want to display the file content then you may use inside your route function something like:
return response()->file('pathToFile');
If download the file is what you want, then try to use instead:
return response()->download('pathToFile');

Resources