I made a bulk update function in controller where I'm saving single value in multiple rows. For example user input is price = 30. Same 30 will go on the rows where id is equal to [1,2,3,4,5,].
In my update form I have a input field price, if I add value="{{ $cart->price }} and send update request with new value like 85. It takes the previous value which is 30.
If I remove the value="{{ $cart->price }} from input for submit button becomes disable. I have tried changing tag to as well. Please help figure out what I am doing wrong.
Here's my input code:
<div class="form-group">
<input type="text" name="price" value="" class="form-control" required>
</div>
Here's my controller:
public function bulkupdate(Request $request)
{
// dd($request);
$this->validate($request, [
'id' => 'required',
'currency_id' => 'required',
'price' => 'required',
'type_id' => 'required',
'country' => '',
'port' => '',
]);
$ids = [$request->input('id')];
$currency_id = $request->input('currency_id');
$price = $request->input('price');
$type_id = $request->input('type_id');
$country = $request->input('country');
$port = $request->input('port');
$status = $request->input('status');
// dd($price);
foreach($ids[0] as $id)
{
$cart = Cart::where('id', $id)->update([
'status' => $status,
'currency_id' => $currency_id,
'price' => $price,
'type_id' => $type_id,
'country' => $country,
'port' => $port,
]);
}
return redirect()->back()->with('success', 'Cart items updates');
}
You don't need to use foreach loop, you can do this by whereIn :
you are sure that all ids are on $ids zero index?
if isn't you can direct give $ids otherwise $ids[0] or $ids is an array so you directly pass $ids in whereIn clause
Cart::whereIn('id', $ids)->update([
'status' => $status,
'currency_id' => $currency_id,
'price' => $price,
'type_id' => $type_id,
'country' => $country,
'port' => $port,
]);
first of all you need to get the record and then UPDATE it.
in your code just change this:
foreach($ids[0] as $id)
{
$cart = Cart::where('id', $id)->first()->update([
'status' => $status,
.
.
.
]);
}
Related
I’m getting this error: Indirect modification of overloaded element of App\Models\ has no effect, change ->get(); to ->first->toArray(); another error Call to a member function toArray() on null
here the code
$penjualan = Penjualan::find(session('id_penjualan'));
$detail = PenjualanDetail::with('produk')->where('id_penjualan', session('id_penjualan'))->get();
$transaction = new Penjualan();
foreach ($detail as $item) {
$transaction_details = [
'order_id' => $penjualan->id_penjualan,
'gross_amount' => $penjualan->bayar,
];
$item_details = [
'id' => $penjualan->id_penjualan,
'price' => $item->harga_jual,
'quantity' => $item->jumlah,
'name' => $item->produk->nama_produk,
];
$customer_details = [
'first_name' => $request->get('uname'),
'last_name' => '',
'email' => $request->get('email'),
'phone' => $request->get('number'),
];
$transaction = [
'transaction_details' => $transaction_details,
'item_details' => $item_details,
'customer_details' => $customer_details,
];
}
$snapToken = Midtrans\Snap::getSnapToken($transaction);
$transaction->snap_token = $snapToken;
$transaction->save();
anyone could help me to fix this?
I have done Midtrans payment before.
The problem you've got with your current code are
you want to store snap_token inside your Penjualan model, but you use new Penjualan()
when multiple items are ordered, your code do not support it cause $item_details is a single array inside foreach loop
So here is an updated code with some notes and recommendations.
$id = session('id_penjualan');
$validated = $request->validate([
'uname' => 'required|string',
// 'lname' => 'nullable|string',
'email' => 'required|string',
'number' => 'required|string',
]);
// use single query to retrieve Penjualan and PenjualanDetail
// for product name, recommend to store it within PenjualanDetail, along with price and base_price
$penjualan = Penjualan::query()
->with('details')
->find($id);
if (!$penjualan) {
// you can redirect your customer to cart or any other page
return redirect('cart')->with('error', 'Can not find Penjualan.');
}
$item_details = [];
foreach ($penjualan->details as $item) {
$item_details[] = [
'id' => $item->id,
'price' => $item->harga_jual,
'quantity' => $item->jumlah,
// recommended product's name to be stored within PenjualanDetail
'name' => $item->nama_produk,
];
}
$transaction_details = [
'order_id' => $penjualan->id_penjualan,
// "bayar" must not contain any decimal, use cast Money
'gross_amount' => $penjualan->bayar,
];
// Optional
$customer_details = [
'first_name' => $validated['uname'],
'last_name' => '', // $validated['lname'],
'email' => $validated['email'],
'phone' => $validated['number'],
// 'billing_address' => '',
// 'shipping_address' => '',
];
// this is a simple array that will be sent to method getSnapToken()
$transaction = [
'transaction_details' => $transaction_details,
'customer_details' => $customer_details,
'item_details' => $item_details,
];
// this method only accept good old array
$snapToken = Midtrans\Snap::getSnapToken($transaction);
$penjualan->snap_token = $snapToken;
// recommend to store your customer detail here, either multiple fields or single array field storing $customer_details
// $penjualan->first_name = $customer_details['first_name'];
// $penjualan->last_name = $customer_details['last_name'];
// $penjualan->email = $customer_details['email'];
// $penjualan->phone = $customer_details['phone'];
// $penjualan->billing_address = $customer_details['billing_address'];
// $penjualan->shipping_address = $customer_details['shipping_address'];
$penjualan->save();
I commented out some parts that you might not use, where I did used them in the past.
Feel free to adjust them to suite your needs.
public function getSnapToken ()
{
$id = session('id_penjualan');
$member = Member::orderBy('nama')->get();
$penjualan = Penjualan::with(['penjualan_detail' => $detail = function ($query) {
$query->where('item', 'kode_produk, subtotal, jumlah, nama_produk');
}])->where('id_penjualan', ('id_penjualan'))
->orderBy('id_penjualan')
->get();
$transaction = array($penjualan);
foreach ( $detail as $item ) {
$transaction_details = [
'order_id' => $this->penjualan->id_penjualan,
'gross_amount' => $this->penjualan->bayar,
];
$item_details = [
'id' => $item->produk->kode_produk,
'price' => $item->jumlah * $item->subtotal,
'quantity' => $item->jumlah,
'name' => $item->produk->nama_produk,
];
$customer_details = [
'id' => $penjualan->member->kode_member,
'first_name' => $validated['uname'],
'last_name' => $validated['lname'],
'email' => $validated['email'],
'phone' => $validated['number'],
// 'billing_address' => '',
// 'shipping_address' => '',
];
$transaction = [
'transaction_details' => $transaction_details,
'item_details' => $item_details,
'customer_details' => $customer_details,
];
}
$snap_token = '';
try {
$snap_token = \Midtrans\Snap::getSnapToken($transaction);
}
catch (\Exception $e) {
echo $e->getMessage();
}
echo "snap_token = ".$snap_token;
}
public function payment(Penjualan $penjualan)
{
$snap_token = $penjualan->snap_token;
if (is_null($snap_token)) {
$midtrans = new CreateSnapTokenService($penjualan);
$snap_token = $midtrans->getSnapToken();
$snap_token = Penjualan::where('id_penjualan')->update(['snap_token' => $snap_token]);
}
return view('penjualan.payment', ['snap_token'=>$snap_token]);
}
I have 3 input tag with type number in blade.php. I want to validate the sum is equal to 100. So, how to do that? Thanks for your help.
Blade.php
<input type="number" name="number1" />
<input type="number" name="number2" />
<input type="number" name="number3" />
Controller
public function store(Request $request) {
$data = $request->validate([
'number1' => 'required',
'number2' => 'required',
'number3' => 'required',
]);
$sum = $data['number1'] + $data['number2'] + $data['number3'];
$myDb = new Mynumber();
$myDb->number1 = $data['number1'];
$myDb->number2 = $data['number2'];
$myDb->number3 = $data['number3'];
$myDb->save();
}
You can extend the validator with a new rule by adding this in a service provider:
$validator->extend("sumsTo", function ($attribute, $value, $parameters) {
$expected = floatval(array_shift($parameters));
$otherParameters = request()->only($parameters);
return floatval(array_sum(array_merge(array_values($otherParameters), [ $value ]))) === $expected;
});
Then you'd use this as:
$request->validate([
'field1' => 'sumsTo:100,field2,field3',
'field2' => 'sumsTo:100,field1,field3'
'field3' => 'sumsTo:100,field1,field2'
]);
This will flag all 3 fields as failed as well.
If you want to stay within the boundaries of Laravels validator, I'd suggest you either use the after validation hook or create a temporary field (within PHP, do NOT use client sided tech for this job!) with the sum of all the necessary fields and validate against it.
$validator = Validator::make([
'field1' => 50,
'field2' => 25,
'field3' => 22,
], [
'field1' => 'required|numeric',
'field2' => 'required|numeric',
'field3' => 'required|numeric',
]);
$validator->after(function ($validator) {
if ($validator->getData()['field1'] + $validator->getData()['field2'] + $validator->getData()['field3'] !== 100) {
$validator->errors()->add('field1', 'Make sure the sum of all fields equals 100.');
}
});
I'm trying to do simple function edit student table field, But its updating only first field: first_name
My controller.
public function editStudent(Request $request)
{
$studId = $request->get('studId');
$studFirstName = $request->get('firstName');
$studLastName = $request->get('lastName');
$studGender = $request->get('gender');
$studBirthday = $request->get('birthday');
$studSchoolId = $request->get('schoolId');
$update = Student::where('id', $studId)->update(['first_name' => $studFirstName],
['last_name' => $studLastName], ['gender' => $studGender], ['birthday', $studBirthday], ['school_id' => $studSchoolId]);
return response()->json([
"update" => $update,
]);
}
Update takes a single array, you're passing in multiple arrays
$update = Student::where('id', $studId)
->update([
'first_name' => $studFirstName,
'last_name' => $studLastName,
'gender' => $studGender,
'birthday'=> $studBirthday,
'school_id' => $studSchoolId
]);
Its better to get the item from DB then update that on a second query:
$student = Student::find($studId);
$student->update([
'first_name' => $request->firstName,
'last_name' => $request->lastName,
'gender' => $request->gender,
'birthday'=> $request->birthday,
'school_id' => $request->schoolId
]);
When I want to edit the post with the post's existing tags it only shows one tag though there are more tags in the selected post. I also want to input new tags in the post-editing blade.
Post creating code
//Store Post
public function storeNewPost(Request $request){
//return $request->all();
$request->validate([
'post_title' => 'required',
'post_details' => 'required',
'category_id' => 'required',
'image' => 'image|max:15360|dimensions:max_width=4000,max_height=3000'
]);
$image = $request->file('post_thumbnail');
$name_gen=uniqid().'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(700,400)->save('frontend/assets/images/post/'.$name_gen);
$save_url = 'frontend/assets/images/post/'.$name_gen;
$post = Post::create([
'user_id' => Auth::id(),
'post_uper_title' =>$request->post_uper_title,
'post_title' =>$request->post_title,
'post_sub_title' =>$request->post_sub_title,
'post_details' =>$request->post_details,
'post_slug' =>str_replace(' ', '-', $request->post_title),
'seo_title' =>$request->seo_title,
'seo_descp' =>$request->seo_descp,
'lead' =>$request->lead,
'lead2' =>$request->lead2,
'featured' =>$request->featured,
'repoter_name' =>$request->repoter_name,
'division_id' =>$request->division_id,
'district_id' =>$request->district_id,
'category_id' =>$request->category_id,
'post_thumbnail' =>$save_url,
'thumbnail_caption' =>$request->thumbnail_caption,
'thumbnail_alt' =>$request->thumbnail_alt,
'created_at' => Carbon::now(),
]);
if($post){
$tags = explode(",", implode($request->tags));
$tagNames = [];
if (!empty($tags)) {
foreach ($tags as $tagName)
{
$tag = Tags::firstOrCreate(['name'=>$tagName]);
if($tag)
{
$tagNames[] = $tag->id;
}
}
}
$post->tags()->sync($tagNames);
$notification = array(
'message' => 'Post Inserted Successfully',
'alert-type' => 'success'
);
return redirect()->route('all.posts')->with($notification);
}else{
return back();
}
}//end insert post
** post update code in post controller **
//Edit Post
public function editPost($news_id){
$editPost = Post::findOrFail($news_id);
$postDivisions = Division::get();
$postCats = Category::get();
$post_dist = District::get();
$post_tags = Tags::all();
return view('admin.post.edit-post', compact('postDivisions', 'postCats', 'editPost', 'post_dist', 'post_tags'));
}
//Update Post
public function updatePost(Request $request){
$news_id = $request->id;
$image = $request->file('post_thumbnail');
$oldimage = $request->oldimage;
if ($image) {
$name_gen=hexdec(uniqid()).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(700,400)->save('frontend/assets/images/post/'.$name_gen);
$save_url = 'frontend/assets/images/post/'.$name_gen;
if($oldimage){
unlink($oldimage);
}
Post::findOrFail($news_id)->update([
'user_id' => Auth::id(),
'post_uper_title' =>$request->post_uper_title,
'post_title' =>$request->post_title,
'post_sub_title' =>$request->post_sub_title,
'post_details' =>$request->post_details,
'post_tags' =>$request->post_tags,
'post_slug' =>$request->post_slug,
'seo_title' =>$request->seo_title,
'seo_descp' =>$request->seo_descp,
'lead' =>$request->lead,
'lead2' =>$request->lead2,
'featured' =>$request->featured,
'repoter_name' =>$request->repoter_name,
'division_id' =>$request->division_id,
'district_id' =>$request->district_id,
'category_id' =>$request->category_id,
'post_thumbnail' =>$save_url,
'thumbnail_caption' =>$request->thumbnail_caption,
'thumbnail_alt' =>$request->thumbnail_alt,
'created_at' => Carbon::now(),
]);
$notification = array(
'message' => 'Post Updated Successfully',
'alert-type' => 'success'
);
return redirect()->route('all.posts')->with($notification);
}else{
Post::findOrFail($news_id)->update([
'user_id' => Auth::id(),
'post_uper_title' =>$request->post_uper_title,
'post_title' =>$request->post_title,
'post_sub_title' =>$request->post_sub_title,
'post_details' =>$request->post_details,
'post_tags' =>$request->post_tags,
'post_slug' =>$request->post_slug,
'seo_title' =>$request->seo_title,
'seo_descp' =>$request->seo_descp,
'lead' =>$request->lead,
'lead2' =>$request->lead2,
'featured' =>$request->featured,
'repoter_name' =>$request->repoter_name,
'division_id' =>$request->division_id,
'district_id' =>$request->district_id,
'category_id' =>$request->category_id,
'post_thumbnail' =>$oldimage,
'thumbnail_caption' =>$request->thumbnail_caption,
'thumbnail_alt' =>$request->thumbnail_alt,
'created_at' => Carbon::now(),
]);
$notification = array(
'message' => 'Post Updated Successfully',
'alert-type' => 'success'
);
return redirect()->route('all.posts')->with($notification);
}
}//end update post
** post editing blade's tags code **
<div class="form-group">
<label class="form-control-label">{{__('Post Tags')}}</label>
<input type="text" class="w-100" id="tagnames" name="tags[]" data-role="tagsinput"
#foreach ($editPost->tags as $tags) value="{{$tags->name}}" #endforeach>
</div>
If you have manyToMany relation in your models use sync() method on update method.
Example:
$post->tags()->sync($request->tags);
// try this
<input type="text" class="w-100" id="tagnames" name="tags[]" data-role="tagsinput" value="#foreach($editPost->tags as $tags){{$tags->name.','}}#endforeach">
Hi I am using RaveFlutterWave as my payment gateway. I want to store an orders whenever a customer finish making payment but I couldn't get pass that error. I don't know what am missing there.
Thanks for your help, here is my code.
public function callback(Request $request)
{
// $data = Rave::verifyTransaction(request()->txref);
$resp = $request->resp;
$body = json_decode($resp, true);
$txRef = $body['data']['data']['txRef'];
$data = Rave::verifyTransaction($txRef);
return redirect()->route('success');
}
Here is my route
Route::get('/success', 'RaveController#addToOrdersTables')->name('success');
and this is my method for saving the order
protected function addToOrdersTables($request, $error)
{
$order = Order::create([
'user_id' => auth()->user() ? auth()->user()->id : null,
'billing_email' => $request->email,
'billing_first_name' => $request->first_name,
'billing_last_name' => $request->last_name,
'billing_address' => $request->address,
'billing_city' => $request->city,
'billing_town' => $request->town,
'billing_postalcode' => $request->postalcode,
'billing_phone' => $request->phone,
'billing_total' => Cart::getTotal(),
'error' => $error,
]);
foreach (Cart::getContent() as $item)
{
OrderProduct::create([
'order_id' => $order->id,
'product_id' => $item->model->id,
'quantity' => $item->quantity,
]);
}
}
Thanks for concern.
You have to pass parameter through route as well:
Route::get('/success/{error}', 'RaveController#addToOrdersTables')->name('success');
And In addToOrdersTables method type hint the request using Request Like given below:
protected function addToOrdersTables(Request $request, $error)