Update Multiple Input Laravel - mysql

How to update multiple inputs in Laravel? I have two tables: Order and Detail_Order. Here's my controller to create multiple inputs.
public function store($id_trip, Request $request){
$order = new Order();
$order->id_trip = $id_trip;
$order->id_users = Auth::guard('operator')->user()->id_users;
$order->date_order = date('Y-m-d H:i:s');
$order->id_users_operator = Auth::guard('operator')->user()->id_users;
$order->save();
foreach($request->passenger_name as $key => $value){
Detail_Order::create([
'id_trip' => $order->id_trip,
'id_seat' => $request->id_seat[$key],
'id_order' => $order->id_order,
'passenger_name' => $request->passenger_name[$key],
'address' => $request->address[$key],
'phone_number' => $request->phone_number[$key]
]);
}
}
I tried to update it, but I don't know how to update the Detail_order. Here's my update controller :
public function update($id_order, $id_trip, Request $request){
$order = Order::where(['id_order' => $id_order, 'id_trip' => $id_trip])->first();
$order->id_trip = $request->id_trip;
$order->id_users = Auth::guard('operator')->user()->id_users;
$order->save();
$detail = Detail_Order::where(['id_order' => $id_order, 'id_trip' => $id_trip])->get();
if(count($request->id_seat) > 0){
for($i = 0; $i < count($request->id_seat); $i++){
$detail[$i]->id_trip = $order->id_trip;
$detail[$i]->id_seat = $request->id_seat[$i];
$detail[$i]->id_order = $pesanan->id_order;
$detail[$i]->passenger_name = $request->passenger_name[$i];
$detail[$i]->address = $request->address[$i];
$detail[$i]->phone_number = $request->phone_number[$i];
$detail[$i]->save();
}
}
session()->flash('flash_success', 'Data has been updated');
return redirect('/order');
}

after $order->save(); line you can do something like this....
if it is work good .. if not you can comment below . i will give you solution...
$order->save();
$detail = Detail_Order::where('order_id', $order->id)->get();
if(count($request->id_seat) > 0){
for($i = 0; $i < count($request->id_seat); $i++){
$detail[$i]->order_id = $order->id;
$detail[$i]->id_seat = $request->id_seat[$i],
$detail[$i]->passenger_name = $request->passenger_name[$i];
$detail[$i]->save();
}
}

Related

convert csv file to json object with Laravel

I am doing a project with Laravel 7. I have to read a csv file and through a controller passing the data in json format to a view.
Unfortunately I don't know how to do that.
These are my controller methods:
public function index($source)
{
$source = strtolower($source);
switch ($source) {
case "csv":
$file_csv = base_path('transactions.csv');
$transactions = $this->csvToJson($file_csv);
dd(gettype($transactions));
return view('transactions', ['source' => $source, 'transactions' => $transactions]);
break;
case "db":
$transactions = Transaction::all();
dd(gettype($transactions));
return view('transactions', ['source' => $source, 'transactions' => $transactions]);
break;
default:
abort(400, 'Bad sintax error.');
}
}
function csvToJson($filename = '', $delimiter = ',')
{
if (!file_exists($filename) || !is_readable($filename)) {
return false;
}
$header = null;
$data = array();
if (($handle = fopen($filename, 'r')) !== false)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== false)
{
if (!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
As you can see, under the two cases I put a dd with a gettype function inside. In the first case I receive uncorrectly the response array, in the second one I receive correctly the response object.
The converted csv file should have this format:
[{"id":1,"code":"T_218_ljydmgebx","amount":"8617.19","user_id":375,"created_at":"2020-01-19T16:08:59.000000Z","updated_at":"2020-01-19T16:08:59.000000Z"},
{"id":2,"code":"T_335_wmhrbjxld","amount":"6502.72","user_id":1847,"created_at":"2020-01-19T16:08:59.000000Z","updated_at":"2020-01-19T16:08:59.000000Z"}]
Do you know how to convert the array transactions into a json object in the first case?
I don't know if there is any build-in solution on Laravel, but it can be done by PHP.
I didn't test my code. So it might not work, or contain some typos, but I'm sure it will give you some directions.
$cols = ["id","code","amount","user_id","created_at","updated_at"];
$csv = file('folder/name.csv');
$output = [];
foreach ($csv as $line_index => $line) {
if ($line_index > 0) { // I assume the the first line contains the column names.
$newLine = [];
$values = explode(',', $line);
foreach ($values as $col_index => $value) {
$newLine[$cols[$col_index]] = $value;
}
$output[] = $newLine;
}
}
$json_output = json_encode($output);
You can just do this :
$csv= file_get_contents($file);
$array = array_map('str_getcsv', explode(PHP_EOL, $csv));
$json json_encode($array);
If you want to return json object
return $json;
If you want to create a .json file
// Pure PHP
$file = fopen('results.json', 'w');
fwrite($file, $json);
fclose($file);
// Laravel using Storage
Storage::disk('local')->put('public/result.json', $json);
I hope this helps somone.
I have an email marketing application where I made bulk importers. So here is their CSV TO JSON code.
function convert_csv_to_json($csv_data){
// CSV to JSON process 1
$context = array(
'http'=>array(
'follow_location' => false,
'max_redirects' => 1000000
)
);
$context = stream_context_create($context);
if (($handle = fopen($csv_data, "r", false, $context)) !== FALSE) {
$csvs = [];
while(! feof($handle)) {
$csvs[] = fgetcsv($handle);
}
$datas = [];
$column_names = [];
foreach ($csvs[0] as $single_csv) {
$column_names[] = $single_csv;
}
foreach ($csvs as $key => $csv) {
if ($key === 0) {
continue;
}
foreach ($column_names as $column_key => $column_name) {
$datas[$key-1][$column_name] = $csv[$column_key];
}
}
return $json = json_encode($datas);
}
// OR
// CSV to JSON process 1
$cols = ['id',
'owner_id',
'name',
'email',
'country_code',
'phone',
'favourites',
'blocked',
'trashed',
'is_subscribed',
'deleted_at',
'created_at',
'updated_at.'];
$csv = file($csv_data);
$output = [];
foreach ($csv as $line_index => $line) {
if ($line_index > 0) { // I assume the the first line contains the column names.
$newLine = [];
$values = explode(',', $line);
foreach ($values as $col_index => $value) {
$newLine[$cols[$col_index]] = $value;
}
$output[] = $newLine;
}
}
return $json_output = json_encode($output);
}

Remove commas when importing excel to mysql

I want to remove commas when importing data from an excel file to the database and i use phpexcel library for importing the data
i have a controller like this for importing the excel file
M_excel.php
public function import(){
$user = $this->ion_auth->user()->row();
include APPPATH.'third_party/PHPExcel/PHPExcel.php';
$excelreader = new PHPExcel_Reader_Excel2007();
$loadexcel = $excelreader->load('excel/'.$this->filename.'.xlsx');
$sheet = $loadexcel->getActiveSheet()->toArray(null, true, true ,true);
$data = array();
$numrow = 4;
foreach($sheet as $row){
if($numrow > 4){
array_push($data, array(
'NO' => $row['A'],
'APIID' => $row['B'],
'Jan19' => $row['C'],
'Feb19' => $row['D'],
'Mar19' => $row['E'],
'Apr19' => $row['F'],
'May19' => $row['G'],
'Jun19' => $row['H'],
'Jul19' => $row['I'],
'Aug19' => $row['J'],
'Sep19' => $row['K'],
'Oct19' => $row['L'],
));
}
$numrow++;
}
$this->m_excel->insert_multiple($data);
redirect("excel_import");
}
Excel file
just replace the comma by using str_replace(",", "", "string here") like below
$data = array();
$i=0;
foreach($sheet as $row){
if($numrow > 4){
$data[$i]['NO'] = $row['A'];
$data[$i]['APIID'] = $row['B'];
$data[$i]['Jan19'] = str_replace(",", "", $row['C']) // use str_replace where you want to replace comma
$data[$i]['Feb19'] = $row['D'];
$data[$i]['Mar19'] = $row['E'];
$data[$i]['Apr19'] = $row['F'];
$data[$i]['May19'] = $row['G'];
$data[$i]['Jun19'] = $row['H'];
$data[$i]['Jul19'] = $row['I'];
$data[$i]['Aug19'] = $row['J'];
$data[$i]['Sep19'] = $row['K'];
$data[$i]['Oct19'] = $row['L'];
}
$i++;
$numrow++;
}
$this->m_excel->insert_multiple($data);
redirect("excel_import");

How to add picture to database with laravel

I am creating Laravel 7 project and I want to add/browse images into/from MySQL database.
The images column names are icon_lg and icon_sm
This is my create function in the Controller I tried it in two ways as I saw in some tutorials:
public function create(Request $request)
{
$object = $this->objectModel::create([
'name' => $request->name,
'icon_sm' => $request->icon_sm
]);
if($request->hasFile('icon_lg')) {
$images = explode(',', $request->hasFile('icon_lg'));
foreach($images as $image)
$filename = rand().'.'.$image->getClientOriginalExtension();
$filePath = public_path("images");
$image->move($filePath, $filename);
return Image::create([
'icon_lg' => $filename,
//'item_id' => $created->id,
]);
}
if ($request->save == 'browse')
return redirect()->route("{$this->objectName}");
elseif ($request->save == 'edit')
return redirect()->route("{$this->objectName}.edit", ['id' => $object]);
elseif ($request->save == 'add')
return redirect()->route("{$this->objectName}.add");
else
return redirect($request->previous_url);
}
It does nothing with icon_lg it inserts null value to it.
And it deals with icon_sm as String.
i think you must set the hasfile validation inside foreach loop like
$images = explode(',', $request->hasFile('icon_lg'));
foreach($images as $image)
if($request->hasFile('icon_lg')) {
$filename = rand().'.'.$image->getClientOriginalExtension();
$filePath = public_path("images");
$image->move($filePath, $filename);
return Image::create([
'icon_lg' => $filename,
//'item_id' => $created->id,
]);
}
just test it without validation first
it should work

How to make update data of mysql in laravel

I'm trying to make an update with values from a form and pass it into an update controller using a route, there's no error given but why there's nothing happen after I updated the data?
Form:
<form action="/update" id="frm_edit" method="post" enctype="multipart/form-data">
Routes:
Route::post('/update', 'EditManga#update'); //update route
Route::post('/admin_page/manga_list', 'Add_Manga_Controller#upload')->name('upload.image');
Route::get('/admin_page/manga_list','ShowData#Manga_list');
Controller:
public function update(Request $request){
$this->validate($request, [
'image' => 'required|image|mimes:jpg,png,jpeg'
]);
//MENGAMBIL FILE IMAGE DARI FORM
$kode_manga = $request->input('kdmanga');
$judul = $request->input('jdmanga');
$alternatif = $request->input('almanga');
$author = $request->input('aumanga');
$status = $request->status;
$lastup = $request->input('lumanga');
$genre = $request->input('grmanga');
$lastc = $request->input('lcmanga');
$sinopsis = $request->input('sinopsis');
$file = $request->file('image');
DB::table('add_manga')->where('kode_manga',$kode_manga)->update([
'judul_manga' => $judul,
'alt_title' => $alternatif,
'author' => $author,
'status' => $status,
'uploaded' => $lastup,
'genre' => $genre,
'latest' => $lastc,
'summary' => $sinopsis
]);
return redirect('/admin_page/manga_list');
}
}
is there any other way or there something's wrong with my code?, Thank you.
In you scenario this another of doing this:
public function update(Request $request, $id)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpg,png,jpeg'
]);
//MENGAMBIL FILE IMAGE DARI FORM
$kode_manga = $request->input('kdmanga');
//getting the target row to updae
$addmanga = DB::table('add_manga')->select('*')
->where('kode_manga',$kode_manga)->get();
$id = $addmanga->id; // getting the id of the target
$add_manga = App\YOUR_MODEL_NAME::find($id);
$add_manga->judul_manga = $request->input('jdmanga');
$add_manga->alt_title = $request->input('almanga');
$add_manga->author = $request->input('aumanga');
$add_manga->status = $request->status;
$add_manga->uploaded = $request->input('lumanga');
$add_manga->genre = $request->input('grmanga');
$add_manga->latest = $request->input('lcmanga');
$add_manga->summary = $request->input('sinopsis');
$add_manga->file = $request->file('image');
$add_manga->save();
return redirect('/admin_page/manga_list');
}
Hope this will work for you!

How do I write a single function in laravel that will be usable for different controllers or schedule commands and access different facades of models

I have this public function below but I will have to write a similar code in about 60 other places, I don't want to repeat myself rather, I want to be able to write a single function such that all I need change is 'Dailysaving::', and '00:00:00' each time I use the function. And please note that I will be creating several other schedule commands which this function should work for. How do I go about this please and where am I supposed to place the function I write And how do I access different models from the function. Thanks in advance for anyone that will help me out.
public function handle()
{
$users= Dailysaving::where('debit_time', '00:00:00')->where('status', 'Active')->get();
//die($users);
foreach ($users as $user) {
$email = $user->email;
$amount = $user->amount_daily * 100;
//Let's know where the payment is on the db
$user_id = $user->user_id;
$savings_id = $user->id;
$auth_code= $user->authorization_code;
//
$metastring = '{"custom_fields":[{"user_id":'. $user_id. '}, {"action": "activatedaily"},{"savings_id": '.$savings_id.'},{"savingstype": "dailysavings"}]}';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.paystack.co/transaction/charge_authorization",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'amount'=>$amount,
'email'=>$email,
'authorization_code' =>$auth_code,
'metadata' => $metastring,
]),
CURLOPT_HTTPHEADER => [
"authorization:Bearer sk_test_656456h454545",
"content-type: application/json",
"cache-control: no-cache"
],
));
$response = curl_exec($curl);
$err = curl_error($curl);
if($err){
$failedtranx = new Failedtransaction;
$failedtranx->error = $err;
$failedtranx->save();
}
if($response) {
$tranx = json_decode($response);
if (!$tranx->status) {
// there was an error contacting the Paystack API
//register in failed transaction table
$failedtranx = new Failedtransaction;
$failedtranx->error = $err;
$failedtranx->save();
}
if ('success' == $tranx->data->status) {
$auth_code = $tranx->data->authorization->authorization_code;
$amount = ($tranx->data->amount) / 100;
$last_transaction = $tranx->data->transaction_date;
$payment_ref = $tranx->data->reference;
$record = new Transactionrecord;
$record->payment_ref = $payment_ref;
$record->save();
//saving complete
//die('saved');
$item = Dailysaving::find($savings_id);
$total_deposit = $item->total_deposit + $amount;
$item->total_deposit = $total_deposit;
$item->last_transaction_date = date('Y-m-d H:i:s');
$target = $item->day_target;
if ($target == $total_deposit) {
$item->status = 'Completed';
}
$item->save();
}
echo 'done';
}
else{
echo 'failed';
}
}
}
As I understand you are trying to make custom helper functions.
So you need create helpers.php with your functions and follow instructions in the below answer: https://stackoverflow.com/a/28290359/5407558