Laravel - How to Update Dynamic Input Fields - laravel

In my Laravel-8, I have this code:
public function add(Request $request){
if( $request->ajax() ){
$rules = array(
'first_name.*' => 'required',
'country.*' => 'required'
);
$error = Validator::make($request->all(),$rules);
if($error->fails()){
return response()->json([
'error' => $error->errors()->all(),
]);
}
$first_name = $request->first_name;
$country = $request->country;
for( $count = 0; $count < count($first_name); $count++ ){
$data = array(
'first_name' => $first_name[$count],
'country' => $country[$count],
);
$insert_data[] = $data;
}
DynamicField::insert($insert_data);
return response()->json([
'success' => 'Data added Successfully',
]);
}
}
This successfully Inserts record.
How do I do the update to this same code?
I mean public function update ...

Related

Image Update Problem Using Laravel Query Builder

My All Data has been updated successfully but Image not update and old image not remove. I am using Query Builder.
Can anyone tell me what to do?
My Controller are given below
I want to know something new.
public function update(Request $request,$id)
{
$validatedData = $request->validate([
'name' => 'required|max:255',
'title' => 'required',
'details' => 'required',
]);
$data = array();
$data['name'] = $request->name;
$data['title'] = $request->title;
$data['details'] = $request->details;
$data['status'] = $request->status;
$image=$request->photo;
if ($image) {
$image_name = str_random(20);
$ext = strtolower($image->getClientOriginalExtension());
$image_full_name = $image_name.'.'.$ext;
$upload_path = 'public/upload/event';
$image_url = $upload_path.$image_full_name;
$success = $image->move($upload_path,$image_full_name);
if ($success) {
$data['photo'] = $image_url;
$img = DB::table('events')->where('id',$id)->first();
$image_path = $img->photo;
$done = unlink($image_path);
$user = DB::table('events')->where('id',$id)->update($data);
if ($user) {
$notification = array(
'messege' => 'Data Updated Successfully',
'alert-type' => 'success'
);
return redirect('admin/event')->with($notification);
}else{
return redirect()->back();
}
}
}else{
return redirect()->back();
}
//return redirect('admin/event')->with($notification);
}

Hi guys, How can I empty a field into the database if I fill in a different field

The case is this, in have two types of discount in my application, these are discount by amount and discount by percentage and vice versa.
Here is my code:
public function update(Request $request, $id)
{
$input = $request->all();
$validator = Validator::make($input, [
'client_id' => 'required|integer',
'date' => 'required|date_format:"Y-m-d',
'status' => 'required|integer',
'currency' => 'required|string',
'payment_type' => 'required|integer',
'description' => 'required|string|max:255',
'note' => 'nullable|string|max:255',
'discount_percent' => 'nullable|numeric|',//exists:earnings,id
'discount_amount' => 'nullable|numeric'
]);
// $length = 7;
// $unique = '#'.str_pad($id,$length,"0", STR_PAD_LEFT);
if($validator->fails()){
return $this->sendError('Validation Error.', $validator->errors());
}
$order = Order::find($id);
$order->client_id= $input['client_id'];
$order->date= $input['date'];
$order->status= $input['status'];
$order->currency= $input['currency'];
$order->payment_type= $input['payment_type'];
$order->description= $input['description'];
$order->save();
for($i=0; $i<count($input['product_id']);$i++)
{
if ($input ['discount_amount'] > 0) {
$input ['discount_percent'] = 0;
}
if ($input ['discount_percent'] > 0) {
$input ['discount_amount'] = 0;
}
$ordProduct = OrderProduct::where('order_id', $id)->where('product_id','=',$input['product_id'][$i])
->update(
['quantity' => $input['quantity'][$i],
'note'=> $input['note'],
'discount_percent'=> $input['discount_amount'] ? $input ['discount_amount'] : 0,
'discount_amount'=>$input['discount_percent'] ? $input ['discount_percent'] : 0,
'percent_id' => $input['percent_id']
]);
}
return $this->sendResponse($order, 'Order updated successfully.');
}
The error I'm getting is that when I save a field the value I assign is not saved and is left at 0.
It should be 0 if a change it but i don't know why is not working.

ErrorException Array to string conversion Laravel

Here is my code in the controller.
I want multiple data to insert into a database but I have a problem with Array:
public function postCreate(Request $request)
{
$data = $request->all();
$lastid = Tr_header::create($data)->id;
if (count($request->id_product) > 0)
{
foreach($request->id_product as $item => $value)
$datax = array(
'id_tr_header' => $lastid,
'id_product' => $request->id_product[$item],
'qty' => $request->qty[$item],
'date_kembali' => $request->date_kembali[$item],
'information' => $request->information[$item],
);
Tr_detail::insert($datax);
}
return redirect()->back();
If you want to insert multiple row at a time try this:
{
$data = $request->all();
$lastid = Tr_header::create($data)->id;
if (count($request->id_product) > 0)
{
$datax = [];
foreach($request->id_product as $item => $value)
array_push($datax ,[
'id_tr_header' => $lastid,
'id_product' => $request->id_product[$item],
'qty' => $request->qty[$item],
'date_kembali' => $request->date_kembali[$item],
'information' => $request->information[$item],
]);
Tr_detail::insert($datax);
}
return redirect()->back();
You are overwritting your $datax variable, you need to create an array of arrays to pass on to your insert() function:
public function postCreate(Request $request)
{
$data = $request->all();
$lastid = Tr_header::create($data)->id;
if (count($request->id_product) > 0) {
$datax = [];
foreach ($request->id_product as $item => $value)
$datax[] = array(
'id_tr_header' => $lastid,
'id_product' => $request->id_product[$item],
'qty' => $request->qty[$item],
'date_kembali' => $request->date_kembali[$item],
'information' => $request->information[$item],
);
Tr_detail::insert($datax);
}
return redirect()->back();
}

laravel 5.2 - store multiple value with sum

I have a 2 table user and reports
Report model
public function user() {
return $this->belongsTo('App\User', 'author_id');
}
User model
public function reports() {
return $this->hasMany('App\Report', 'author_id');
}
In User model there is a column called "sum_sales"
In Report model there is a column called "total"
Ho can I pass the sum(total) from my Report model to 'sum_total' inside my User model?
My report controller
public function store(Request $request)
{
$this->validate($request, ['title' => 'required',
'date' => 'required|date_format:d/m/Y|regex:/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/',
'image_1' => 'required|mimes:png,jpeg',
'products' => 'required',
'total' => 'required',
'time' => 'required|min:2',
'location' => 'required',
'sub_location' => 'required',
]);
$user = Auth::user()->id;
$report = new Report($request->all());
$report->author_id = $user;
$image = $request->file('image_1');
$destinationPath = 'uploads/reports';
$ext = $image->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$ext;
$report->image_1 = $image->move($destinationPath, $fileName);
$field_total = $request->input('total');
$sum_total = $report->sum('total');
$totalSum = $field_total + $sum_total;
$report->author_id->sum_sales = $totalSum;
$report->save();
Session::flash('flash_message', 'Report added!');
return redirect('dash/reports');
}
With this the browser say:
Indirect modification of overloaded property App\Report::$author_id has no effect
How can I figure out?
solved by Giedrius Kiršys
public function store(Request $request)
{
$this->validate($request, ['title' => 'required',
'date' => 'required|date_format:d/m/Y|regex:/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/',
'image_1' => 'required|mimes:png,jpeg',
'products' => 'required',
'total' => 'required',
'time' => 'required|min:2',
'location' => 'required',
'sub_location' => 'required',
]);
$user = Auth::user()->id;
$report = new Report($request->all());
$report->author_id = $user;
$image = $request->file('image_1');
$destinationPath = 'uploads/reports';
$ext = $image->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$ext;
$report->image_1 = $image->move($destinationPath, $fileName);
$report->save();
$sumUserTotal = User::find($user)->reports->sum('total');
Auth::user()->update(['sum_sales' => $sumUserTotal]);
Session::flash('flash_message', 'Report added!');
return redirect('dash/reports');
}

codeigniter transaction is not working

I am using codeigniter transaction. i wrote a function but it is not working.It was supposed to complete the transaction while submitting my form. Now its not saving with this code.with out transition code it is working. how can i fix this:
public function twotable_insertData() {
$this->db->trans_start();
$data = array(
'brand_name' => $this->input->post('f_name'),
'brand_user_name' => $this->input->post('l_name'),
);
$brand_id = $this->m_common->insert_row('brands', $data);
echo '$brand_id';
$data1 = array(
'brand_id' => $brand_id,
'stadium_id' => $this->input->post('stadium'),
'concession_stand_no' => $this->input->post('con_std_no'),
);
$this->m_common->insert_row('concession_stands', $data1);
redirect('backend/brand/view_brand');
if ($this->db->trans_status() === FALSE) {
$this->db->trans_rollback();
} else {
echo $this->db->trans_complete();
}
}
I have updated your query...
$this->db->trans_start();
$data = array(
'brand_name' => $this->input->post('f_name'),
'brand_user_name' => $this->input->post('l_name')
);
$brand_id = $this->m_common->insert_row('brands', $data);
// echo '$brand_id';
$data1 = array(
'brand_id' => $brand_id,
'stadium_id' => $this->input->post('stadium'),
'concession_stand_no' => $this->input->post('con_std_no')
);
$this->m_common->insert_row('concession_stands', $data1);
$this->db->trans_complete();
if($this->db->trans_status() === FALSE){
// Check if transaction result successful
$this->db->trans_rollback();
$this->session->set_flashdata('failure', 'Transaction Fails.');
}else{
$this->db->trans_complete();
$this->session->set_flashdata('success', 'Transaction Success.');
}
redirect('backend/brand/view_brand');

Resources