Split one function into two - php

for the reusability, I plan to split my function into two functions. Basically, the concept of the function is loads the input file then preview the data.
Working Code
public function uploadImportCsv()
{
$file = Input::file('file');
$extension = $file->getClientOriginalExtension();
$filename = sha1($file->getClientOriginalName().time()) . ".{$extension}";
//upload to s3
#doing upload to s3
$data = [
'title'=>[],
'value'=>[]
];
$results = Excel::load(Input::file('file'), function($reader){
})->get();
foreach ($results as $result) {
foreach ($result as $key => $value) {
if(!in_array($key, $data['title'])){
array_push($data['title'], $key);
}
}
array_push($data['value'], $result);
}
return Response::json(['filename' => $filename, 'data' => $data]);
}
after split
public function previewCsv()
{
//Preview table
$data = [
'title'=>[],
'value'=>[]
];
$results = Excel::load(Input::file('file'), function($reader){
})->get();
foreach ($results as $result) {
foreach ($result as $key => $value) {
if(!in_array($key, $data['title'])){
array_push($data['title'], $key);
}
}
array_push($data['value'], $result);
}
return Response::json(['data' => $data]);
}
public function uploadImportCsv()
{
$file = Input::file('file');
$extension = $file->getClientOriginalExtension();
$filename = sha1($file->getClientOriginalName().time()) . ".{$extension}";
//upload to s3
#doing upload to s3
$data = $this->previewCsv();
return Response::json(['filename' => $filename,'data' => $data]);
}
I called the function from the preview function but it does not work.

If you need same result, it's not necessary to return a json object from previewCsv funtion.
public function previewCsv()
{
....
return $data;
}

Related

Multiple file upload and location store using laravel

I have an app which stores music from user. User can upload multiple files at once. But while adding this code, the database and the controller only uploads the first file, discarding other files. I need to solve this problem. Any solutions?
UploadController.php
public function store(Request $request)
{
//This is a complex way to store user id. If any easy way, then help me.
$curruser = auth()->user();
$userid = $curruser->id;
$songs = $request->file('songs');
$paths = [];
if(!empty($songs)){
foreach ($songs as $song){
$filename = $song->getClientOriginalName();
$filesize = $song->getSize();
$extension = $song->getClientOriginalExtension();
$paths[] = $song->storeAs('songs',$filename);
$path = new MusicUpload(array(
'user_id' => $userid,
'filename' => $filename,
'extension' => $extension,
'filesize' => $filesize,
));
$path->save();
$paths[] = $path;
return redirect('/fileupload')->with('success','Uploaded successfully');
}
}
}
And also I cannot store the location of the file in the mysql server. Any ideas to do that also. Thanks
Use this
public function store(Request $request)
{
$input = $request->all();
$rules = array(
'songs.*' => 'required|mimes:jpeg,png,jpg,doc,docx,pdf,mp4,mov,ogg,qt', //etc
);
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
$arr = array("status" => 400, "message" => $validator->errors()->first(), "data" => array());
} else {
try {
$datas = [];
$result = [];
if ($request->hasfile('songs')) {
foreach ($request->file('songs') as $key => $file) {
$name = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$filesize = $file->getSize();
$input['songs'] = time() .uniqid().'.' . $file->getClientOriginalExtension();
$file->move(public_path() . '/images', $input['songs']); // your file path
$datas[$key] = $name;
$datas[$key] = $extension;
$datas[$key] = $filesize;
$file = new MusicUpload();
foreach ($datas as $data) {
$file->user_id = Auth::user()->id;
$file->filename = $name;
$file->extension = $extension;
$file->filesize = $filesize;
$file->save();
}
}
}
$arr = array("status" => 200, "message" => "success", "data" => $output);
} catch (\Exception $ex) {
if (isset($ex->errorInfo[2])) {
$msg = $ex->errorInfo[2];
} else {
$msg = $ex->getMessage();
}
$arr = array("status" => 400, "message" => $msg, "data" => array());
}
}
return \Response::json($arr);
}
Just return the redirection after foreach loop has completed.
public function store(Request $request)
{
//This is a complex way to store user id. If any easy way, then help me.
$curruser = auth()->user();
$userid = $curruser->id;
$songs = $request->file('songs');
$paths = [];
if(!empty($songs)){
foreach ($songs as $song){
$filename = $song->getClientOriginalName();
$filesize = $song->getSize();
$extension = $song->getClientOriginalExtension();
$paths[] = $song->storeAs('songs',$filename);
$path = new MusicUpload(array(
'user_id' => $userid,
'filename' => $filename,
'extension' => $extension,
'filesize' => $filesize,
));
$path->save();
$paths[] = $path;
}
return redirect('/fileupload')->with('success','Uploaded successfully');
}
}

Need csv file upload to fetch all rows but currently fetching the first row

This is the code to the upload function in my controller.The problem at hand is that when i upload the csv file to my database I only get(fetch) the first row of the file and the rest of the rows are omitted.I need to be able to get all the rows from the file.Please assist in anyway you can...Thanks in advance
public function upload(Request $request)
{
//get file
//$allowed = array('csv');
$upload=$request->file('upload');
//$extension = File::extension($upload);
$filePath=$upload->getRealPath();
//open and read
$file=fopen($filePath,'r');
$header= fgetcsv($file);
$escapedHeader=[];
//validate
foreach ($header as $key => $value) {
$lheader= strtolower($value);
$escapedItem=preg_replace('/[^a-z]/', '', $lheader);
array_push($escapedHeader, $escapedItem);
}
//looping throught other columns
while ($columns=fgetcsv($file)) {
if ($columns[0]=="")
{
continue;
}
$data= array_combine($escapedHeader, $columns);
dd($data);
//setting type
foreach ($data as $key => $value) {
$value=($key=="phone" || $key=="nationalid" || $key=="staffsalary")?(integer)$value:(string)$value;
}
//table update
$firstname=$data['firstname'];
$lastname=$data['lastname'];
$email=$data['email'];
$phone=$data['phone'];
$nationalid=$data['nationalid'];
$staffid=$data['staffid'];
$stafftitle=$data['stafftitle'];
$staffsalary=$data['staffsalary'];
$employees= Employees::firstOrNew(['phone'=>$phone,'nationalid'=>$nationalid]);
$employees->firstname=$firstname;
$employees->lastname=$lastname;
$employees->email=$email;
$employees->staff_id=$staffid;
$employees->staff_title=$stafftitle;
$employees->staff_salary=$staffsalary;
$employees->employer_phone = Auth::user()->phone;
$employees->save();
return redirect()->route('home');
}
}
The main reason you're having this issue is because your return redirect()->route('home'); is inside your while loop. Just move it so it's on the outside and it should work fine.
Also, this is just an FYI but you could use Collections to clean your controller up a little but:
public function upload(Request $request)
{
$upload = $request->file('upload');
$csv = collect(array_map('str_getcsv', file($upload->getRealPath())));
$keys = array_map(function ($item) {
return preg_replace('/[^a-z]/', '', strtolower($item));
}, $csv->shift());
$csv
->map(function ($row) use ($keys) {
return array_combine($keys, $row);
})
->reject(function ($row) {
return empty(array_first($row));
})
->each(function ($row) {
$row = array_map(function ($value, $key) {
return in_array($key, ['phone', 'nationalid', 'staffsalary']) ? (integer)$value : (string)$value;
}, $row);
$employees = Employees::firstOrNew(['phone' => $row['phone'], 'nationalid' => $row['nationalid']]);
$employees->firstname = $row['firstname'];
$employees->lastname = $row['lastname'];
$employees->email = $row['email'];
$employees->staff_id = $row['staffid'];
$employees->staff_title = $row['stafftitle'];
$employees->staff_salary = $row['staffsalary'];
$employees->employer_phone = Auth::user()->phone;
$employees->save();
});
return redirect()->route('home');
}
Obviously, you don't have to use the code above, I just thought I'd show you an alternative way to write it.
I wasn't sure what if ($columns[0]=="") was there for but I've added that in with the reject() method.
Hope this helps!
Your problem is a different breakline for different OS. Use this construction for better:
// take care of all possible newline-encodings in input file
$NEWLINE_RE = '/(\r\n)|\r|\n/';
$csv = preg_replace($NEWLINE_RE,'===BREAK===', $old_csv);
foreach (explode('===BREAK===', $csv) as $k => $line){
if(strlen($line) > 0) $lines[] = stripcslashes(trim($line));
}

fopen creates file like Resource id #3?

i am trying yo create a new file using a existing file.
but When i create a new file in my uploads folder a file is automatically created with resource id #3 WHY??
public function edit_ini_custom($id)
{
/*Getting parameters name to display in view*/
$this->data['params'] = $this->parameter_m->get();
/*Path of our BASE and CUSTOM INI files*/
$path = "./uploads/";
$this->db->select('*');
$this->db->where('id',$id);
/*Here the id is the ID we got from URI View*/
$this->db->from('base_ini');
$query = $this->db->get();
$result = $query->row();
$filename= $result->base_ini_filename;
$path= $result->file_path;
/*Reading Contents from our path and the name of file we got from database*/
file_get_contents($path.$filename);
$this->data['parameters'] = parse_ini_file($path.$filename);
/*Getting Our POST DATA from View*/
$data = array(
'SipUserName' => $this->input->post('SipUserName') ,
'SipAuthName' => $this->input->post('SipAuthName'),
'DisplayName' => $this->input->post('DisplayName'),
'Password' => $this->input->post('Password'),
'Domain' => $this->input->post('Domain'),
'Proxy' => $this->input->post('Proxy'),
'Port' => $this->input->post('Port'),
'ServerMode' => $this->input->post('ServerMode'),
'Param_1' => $this->input->post('Param_1'),
'Param_2' => $this->input->post('Param_2')
);
$this->load->helper('file');
$suffix =$this->input->post('SipUserName');
/*Setting the Name of File*/
$name =$this->session->userdata('username');
/*Creating New file with the name of customer loggedin*/
$file_new = fopen('uploads/'.$name.$suffix.'.ini', 'w');
fwrite($file_new, "[INIDetails]\n");
foreach ($data as $key => $value)
{
fwrite($file_new, " $key = $value\n");
}
fclose($file_new);
/*Setting path to New CUSTOM file with customer name as prefix*/
$file = $path.$file_new;
function write_php_ini($array, $file)
{
$res = array();
foreach($array as $key => $val)
{
if(is_array($val))
{
$res[] = "[$key]";
foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
}
else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
}
safefilerewrite($file, implode("\r\n", $res));
}
function safefilerewrite($fileName, $dataToSave)
{ if ($fp = fopen($fileName, 'w'))
{
$startTime = microtime(TRUE);
do
{ $canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if(!$canWrite) usleep(round(rand(0, 100)*1000));
} while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5));
//file was locked so now we can store information
if ($canWrite)
{ fwrite($fp, $dataToSave);
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
/*Creates ini file, dumps array to string and creates .INI file*/
write_php_ini($data,$file);
/*Back to you index page id data is submmited*/
if(isset($_POST['submit'] ))
{
redirect('customer/upload_ini/index');
}
$this->data['subview'] = 'customer/upload/edit_ini_custom';
$this->load->view('customer/_layout_main', $this->data);
}

Returning JSON after a query in yii

I'm new to yii framework. I'm just trying to implement Restful APIs. In the simple case scenario (after following some tutorial) I've succeeded with this:
$result = [];
foreach($this->getData() as $record) {
$result[] = $record->getAttributes();
}
return $result;
Note that getData() is a built-in method. Where when trying to use queries for more advanced scenarios, it's done this way:
$attributeNames = 'udid,model,appverionid';
$connection = Yii::app()->db;
$command = $connection->createCommand('select ' . $attributeNames . ' from device');
$models = $command->queryAll();
$attributeNames = explode(',', $attributeNames);
$rows = array();
foreach ($models as $model) {
$row = array();
foreach ($attributeNames as $name) {
$row[$name] = CHtml::value($model, $name);
}
$rows[] = $row;
}
return $rows;
Is that the best practice to return get JSON from queries results, or maybe it can be done in a better way?
Update:
The final response is returned from the following method:
private function sendAjaxResponse(AjaxResponseInterface $interface)
{
$success = count($interface->getErrors()) === 0;
$responseCode = $success ? 200 : 404;
header("content-type: application/json", true, $responseCode);
echo json_encode([
'success' => $success,
'data' => $interface -> getResponseData(),
'errors' => $interface -> getErrors()
]);
Yii::app()->end();
}
And I found out that only these lines are sufficient:
$attributeNames = 'udid,model,appverionid';
$connection = Yii::app()->db;
$command = $connection->createCommand('select ' . $attributeNames . ' from device');
$models = $command->queryAll();
return $models;
The other part (the nested loop) seems for encoding with relations (see here) Then my question is what is encoding with relations and when it is helpful?
The Yii way of creating JSOn data is using CJson library
$query = "'select ' . $attributeNames . ' from device'";
$command = Yii::app()->db->createCommand($query);
$result = $command->queryAll();
$ret = array_values($result);
/* or ...
$ret = array();
foreach ($models as $model) {
$ret = array();
foreach ($attributeNames as $name) {
$row[$name] = CHtml::value($model, $name);
}
$ret[] = $row;
}
*/
echo CJSON::encode($ret);
Yii::app()->end();
I think you simply need to encode the value before return
foreach ($models as $model) {
$row = array();
foreach ($attributeNames as $name) {
$row[$name] = CHtml::value($model, $name);
}
$rows[] = $row;
}
return json_encode($rows);
Very Simple! Just add this line - \Yii::$app->response->format = \yii\web\Response:: FORMAT_JSON; in your method at start and do other code
normally.
for example,
public function actionHospitals()
{
\Yii::$app->response->format = \yii\web\Response:: FORMAT_JSON;
$hospitals = Hospitals::find()->select('speciality')->distinct()->all();
return ['hospitals' => $hospitals];
}

Export whole table to CSV using laravel

I am new to laravel and having a tough time figuring out a way to export one table to csv.
I have tried the following code in the controller class, but it gives me an error:
public function get_export()
{
$table = Cpmreport::all();
$file = fopen('file.csv', 'w');
foreach ($table as $row) {
fputcsv($file, $row);
}
fclose($file);
return Redirect::to('consolidated');
}
Model Class for Cpmreport:
class Cpmreport extends Eloquent
{
public static $table='cpm_report';
}
The error :
Message:
fputcsv() expects parameter 2 to be array, object given
Location:
C:\xampp\htdocs\cpm_report\application\controllers\cpmreports.php on line 195
Any help would be appreciated.
Easy way
Route::get('/csv', function() {
$table = Cpmreport::all();
$output='';
foreach ($table as $row) {
$output.= implode(",",$row->toArray());
}
$headers = array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="ExportFileName.csv"',
);
return Response::make(rtrim($output, "\n"), 200, $headers);
});
fputcsv($file, $table); should be fputcsv($file, $row), shouldn't it?
And convert the object to an array using Eloquent's to_array()method: http://laravel.com/docs/database/eloquent#to-array
public function get_export()
{
$table = Cpmreport::all();
$file = fopen('file.csv', 'w');
foreach ($table as $row) {
fputcsv($file, $row->to_array());
}
fclose($file);
return Redirect::to('consolidated');
}
Select query of MySQL data.
$data = \DB::connection('mysql')->select($select);
Call following function:
query_to_csv($data, 'data.csv');
function data_to_csv($data, $filename)
{
$fp = fopen($filename, 'w');
foreach ($data as $row) {
fputcsv($fp, $row);
}
fclose($fp);
}
0.1 Million records takes 1 second to create.
this is better and simple.
$file_name = "abc";
$postStudent = Input::all();
$ck = DB::table('loan_tags')->select('LAN')->where('liabilitiesId', $postStudent['id'])->get();
$i = 0;
foreach ($ck as $row) {
$apps[$i]['LAN'] = $row->LAN;
$apps[$i]['Account_number'] = $postStudent['account_number'];
$apps[$i]['Bank_Name'] = $postStudent['bank_name'];
$i++;
}
ob_end_clean();
ob_start();
Excel::create($file_name, function($excel) use($apps){
$excel->sheet('Sheetname', function($sheet) use($apps){
$sheet->row(1, array(
'LAN', 'Account number' , 'Bank Name'
));
$k = 2;
foreach ($apps as $deta) {
$sheet->row($k, array($deta['LAN'], $deta['Account_number'], $deta['Bank_Name']
));
$k++;
}
});
})->download('xlsx');

Categories