Matching data between csv and mysql table using Laravel - laravel

How can I read an excel file and compare each reference from my CSV file in my database. I specify that the CSV file and my database contain the same fields (customer number, transaction amount, currency, reference and status). I will retrieve transactions with the same reference but different status.
public function upload_file(Request $request){
$file = file($request->file->getRealPath());
$data = array_slice($file,1);
$parts = (array_chunk($data, 1000));
foreach ($parts as $index => $part) {
$fileName = public_path('excel/'.date('d-m-y-H-i-s').$index. '.csv');
file_put_contents($fileName, $part);
}
(new ExcelUploadTransaction())->importToDb();
return redirect()->route('supportone.import_excel');
}
public function importToDb(){
$path = public_path('excel/*.csv');
$files = glob($path);
foreach ($files as $file) {
$data = array_map('str_getcsv', file($file));
foreach ($data as $row) {
ExcelUploadTransaction::create([
'customer_details'=>$row[0],
'amount'=>$row[1],
'currency'=>$row[2],
'telco_reference'=>$row[3],
'status'=>$row[4]
]);
}
unlink($file);
}
}
public function compare(){
$db_csv = DB::connection('mysql3')->table('excel_upload_transactions')->select('telco_reference','status')->get();
$db_table = DB::table('transac')->select('telco_reference','status')->where('telco_reference',$telco_reference)->get();
$collection = collect($db_csv);
$diff = $collection->diff($db_table);
$diff->all();
return view('supportone.transactions.update.multiple',compact('rows','header'));
}

Related

I am trying to send multiple title and multiple files into database using laravel but i am getting error

I am trying to send multiple title and multiple files into database using laravel but i am getting error please help me how can i resolve this issue ? thanks.
getting error
Cannot use object of type Illuminate\Http\UploadedFile as array
CONTROLLER
public function store(Request $request)
{
foreach ($request->title as $key => $value) {
$audiodetail = new AudioDetail;
$extension = Str::random(40) . $request->file('audio_file_upload')->getClientOriginalExtension();
$audiodetail->audio_file = Storage::disk('audiofile')->putFileAs('', $request->audio_file_upload[$key], $extension);
$audiodetail->title = $value;
$audiodetail->audio_id = $event->id;
$audiodetail->save();
}
return redirect()->route('events');
}
title and audio_file_upload both are different array. So you need to combine both :
public function store(Request $request)
{
$data = array_combine($request->title, $request->audio_file_upload);
foreach ($data as $value) {
$audiodetail = new AudioDetail;
$extension = Str::random(40) . $value['audio_file_upload']->getClientOriginalExtension();
$audiodetail->audio_file = Storage::disk('audiofile')->putFileAs('', $value['audio_file_upload'], '.' . $extension);
$audiodetail->title = $value['title'];
$audiodetail->audio_id = $event->id;
$audiodetail->save();
}
return redirect()->route('events');
}

Laravel: How to return JSON response when using foreach

I am uploading images using Vue and my Laravel backend endpoint looks like this below. I am unsure of what to put in the response though since it is a foreach that iterates through each file and uploads them but I still want to return the response as JSON.
public function upload(Request $request)
{
$files = $request->file('images');
foreach ($files as $file) {
Storage::put('store/assets/', file_get_contents($file->getRealPath()), ['visibility' => 'public']);
}
return response()->json(????);
}
public function upload(Request $request)
{
$files = $request->file('images');
$stack = [];
foreach ($files as $file) {
$fileName = Storage::put('store/assets/', file_get_contents($file->getRealPath()),
['visibility' => 'public']);
array_push($stack, $fileName);
}
return response()->json($stack);
}
Or you can just do like that:
$data = ["success" => 1];
return response()->json($data);
My offer:
if your query is executed succesfully
$data=[
"stat"=>1,
"data"=>[
"first"=>1,
...
]
]
else
$data=[
"stat"=>0,
"error"=>"Not successfull"
]

how to show unix timestamp in blade view from created_at or updated_at field in database laravel?

I want to get UNIX timestamp or convert created_at or updated_at date to UNIX timestamp format from database fields (created_at and updated_at) in laravel 5.8 , how can i do this?
this is my code in my controller :
public function viewArchives(){
$data = Archive::select(‘created_at’)->get();
return view(‘view.archives’, compact(‘data’));
}
and in view/archives.blade.php :
<?php echo $data;?>
the result is :
{“created_at”:”2019-03-17 19:10:30″}
but i want the result be like this :
{“created_at”:”1552849830″}
how can get this result?
$string = '2019-03-17 19:10:30';
$obj = new stdClass;
$obj->created_at = $string;
$collection = [$obj];
foreach ($collection as $k => &$v) {
$collection[$k]->created_at = strtotime($v->created_at);
}
//var_dump($collection);
or
$string = '2019-03-17 19:10:30';
$obj = new stdClass;
$obj->created_at = $string;
$collection = [$obj];
array_walk($collection, function (&$item, $key) {
$item->created_at = strtotime($item->created_at);
});
//var_dump($collection);
Or in your case
public function viewArchives()
{
$data = Archive::select('created_at')->get();
foreach ($data as $k => &$v) {
$v->created_at = strtotime($v->created_at);
}
return view('view.archives', compact('data'));
}
or
public function viewArchives()
{
$data = Archive::select('created_at')->get();
array_walk($data, function (&$item, $key) {
$item->created_at = strtotime($item->created_at);
});
return view('view.archives', compact('data'));
}
This is good place to use array_walk() function.
Add strtotime() view/archives.blade.php :
<?php echo strtotime( $data );?>
With an Eloquent Model one can actually define the $casts per column:
class SomeModel extends Model
{
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'created_at' => 'datetime'
];
}
If you want epoch timestamps instead, just remove this cast (which is likely present).
When the timestamp isn't from any Eloquent Model, one still can render it with Blade:
#php
$dt = new DateTime();
echo $dt->setTimestamp( $timestamp )->format("Y-m-d H:m:s");
#endphp
Or the other way around:
#php
echo strtotime( $isodate );
#endphp

Laravel: export searched data to the excel

I want to export searched data to the laravel below is my controller
public function getUsageData(Request $request)
{
$start_date = $request->get('start_date');
$end_date = $request->get('end_date');
$particulars = DB::table('particulars')
->join('reqs', 'particulars.particular_id', "=", 'reqs.particular_id')
->whereBetween('date_applied', [$start_date, $end_date])
->select('particulars.item_name', 'particulars.unit', 'particulars.price', 'reqs.quantity_issued',
DB::raw('particulars.price*reqs.quantity_issued AS total_cost'))
->get();
if ($particulars->isEmpty()) {
return "No Records Found...................... ";
} else {
$pdf = PDF::loadView('issuer.getUsageReport', ['particulars' => $particulars]);
return $pdf->stream('getUsageReport.issuer');
}
}
I want to retrieve those data to the excel instead of pdf please help
Replace the two PDF lines in the else { ... } statement with:
$list = $particulars->toArray();
//This line adds headers if present in your data
array_unshift($list, array_keys($list[0]));
$callback = function() use ($list) {
$FH = fopen('php://output', 'w');
foreach ($list as $row) {
fputcsv($FH, $row);
}
fclose($FH);
};
return response()->streamDownload($callback,"filename.csv");
Depending on the structure of particulars you may need to do some manipulation to the data first, e.g. flattening. Comment below if so.

Only the last record being recieved is being saved to the database

I am using Angular2 for my frontend and laravel for my back end. I am trying to parse an array and store all of it into different rows but currently only the last record being recieved is being saved to the database.
public function SaveOrder(Request $request) {
$input = $request->all();
$order = new Order;
foreach ($input as $arr) {
foreach ($arr as $key => $value) {
if (array_key_exists($key, $arr) && !empty($value)) {
$order->$key = $value;
}
}
}
$order->save();
}
$input = $request->all();
foreach ($input as $arr) {
var_dump($arr);
foreach ($arr as $key => $value) {
if (array_key_exists($key, $arr) && !empty($value)) {
}
}
}
var_dump of the array
If you take a closer look, you'll notice your SaveOrder method loops through the given collection, sets the $order->$key = $value for productName and productDesc - and in the next iteration overwrites these values. That's why, when you save() the Order model, all you're inserting is the last (iterated) pair of values.
What you should do is to build an array of arrays, containing all "rows" to insert, and then perform a bulk insert.
Thanks #lesssugar I figured it out although I am having second thoughts of doing it this way since it seems inefficient
public function saveOrder(Request $request) {
$input = $request->all();
foreach ($input as $arr) {
foreach ($arr as $key => $value) {
if (array_key_exists($key, $arr) && !empty($value)) {
$data = array($arr);
}
}
DB::table('test')->insert($data);
}
}

Resources