Update multiple table - php

How do I update the two tables, I have 2 tables, order and product, I want to update the product data on the order, I do it with the following code, but the product doesn't want to update
public function update(Request $request, $id , Product $product)
{
$request->validate([
'do_code' => 'required',
'delivery_date' => 'required',
'qty' => 'required',
'user_id' => 'required',
'customer_id' => 'required',
'armada_id' => 'required',
'send_from_id' => 'required',
]);
$data = Delivery_order::find($id);
$data->update($request->all());
if (count($request->product_name) > 0) {
foreach ($request->product_name as $item => $v) {
$data2 = array(
'order_id' => $id,
'product_name' => $request->product_name[$item],
'qty' => $request->qty[$item],
'tonise' => $request->tonise[$item]
);
$product->update($data2);
}
}
return redirect('/do')->with('success', 'Data Successfully Updated');
}

Use just like this
$product->order_id = $id,
$product->product_name = $request->product_name[$item],
$product->qty = $request->qty[$item],
$product->tonise = $request->tonise[$item]
$product->save();

I think, you can use Laravel Relationship to update the second table.

Related

Laravel store and update form

I would like to update a form, I mentioned that the form is already saved in the database(function store). I want to edit the form and update it in the database(function update).
I only want to UPDATE the "tags", this is giving me an error because it is in another table.
I would need your help because I can't do it, I tried different methods but didn't succeed.
public function store(Request $request)
{
// process the listing creation form
$validationArray = [
'title' => 'required',
'company' => 'required',
'logo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:9048',
'location' => 'required',
'service' => 'required',
'apply_link' => 'required|url',
'content' => 'required',
'payment_method_id' => 'required'
];
if (!Auth::check()) {
$validationArray = array_merge($validationArray, [
'email' => 'required|email|unique:users',
'password' => 'required|confirmed|min:5',
'name' => 'required',
'phone' => 'required|numeric|min:10|starts_with:0'
]);
}
$request->validate($validationArray);
// is a user signed in ? if not, create one and authenticate
$user = Auth::user();
if (!$user) {
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'phone' => $request->phone
]);
$user->createAsStripeCustomer();
Auth::login($user);
}
// process the payment and create the listing
try {
$amount = 9900; // $99.00 USD in cents
if ($request->filled('is_highlighted')) {
$amount += 1000;
}
$user->charge($amount, $request->payment_method_id);
$md = new \ParsedownExtra();
$listing = $user->listings()
->create([
'title' => $request->title,
'slug' => Str::slug($request->title) . '-' . rand(1111, 9999),
'company' => $request->company,
'logo' => basename($request->file('logo')->store('public')),
'location' => $request->location,
'apply_link' => $request->apply_link,
'content' => $md->text($request->input('content')),
'is_highlighted' => $request->filled('is_highlighted'),
'is_active' => true
]);
**foreach (explode(',', $request->tags) as $requestTag) {
$tag = Tag::firstOrCreate([
'slug' => Str::slug(trim($requestTag))
], [
'name' => ucwords(trim($requestTag))
]);
$tag->listings()->attach($listing->id);
}**
foreach (explode(',', $request->service) as $requestService) {
$service = Service::firstOrCreate([
'service_name' => ucwords(trim($requestService))
]);
$service->listings()->attach($listing->id);
}
return redirect()->route('user.dashboard')->with('success', 'Anuntul tau a fost publicat!');
} catch (\Exception $e) {
return redirect()->back()
->withErrors(['error' => $e->getMessage()]);
}
} $tag->listings()->attach($listing->id);
}
public function edit($id)
{
$listing = Listing::findOrFail($id);
if (Auth::check() && Auth::user()->id == $listing->user_id) {
$listing = DB::table('listings')
->where('id', $id)
->first();
return view('listings.edit', compact('listing'));
} else {
return (redirect('/dashboard'));
}
}
public function update(Request $request, $id)
{
//working in progress...
$this->validate($request,[
'title' => 'required',
'company' => 'required',
'logo' => 'file|max:2048|required|mimes:jpeg,jpg,png',
'location' => 'required',
'apply_link' => 'required|url',
'content' => 'required'
// 'payment_method_id' => 'required'
]);
$data = Listing::find($id);
$data->title = $request->title;
$data->company = $request->company;
$data->logo = basename($request->file('logo')->store('public'));
$data->location = $request->location;
$data->apply_link = $request->apply_link;
$data['tags'] = explode(',', $request->tags); // <-this one
$data->content= $request->content;
// $data['is_highlighted'] = $request->is_highlighted;
$data['user_id'] = Auth::user()->id;
$data->save();
// DB::table('listings')->where('id', $id)->update($data);
return redirect()->back()->with('success', 'success');
}

Laravel 8 update product in cart if exists

I'm using a Laravel 8 with darryldecode/laravelshoppingcart Cart Package. I'm struggling a bit with updating product quantity if it exists in users cart.
For example: If cart is empty, while adding a product and then clicking mutliple times on "Add To Cart" it adds only one product and then updates quantity to its maximum. But when I'm adding a second product, and then adding again product 1 it adds another product to the cart. It definitely should not add another product but it has to be restricted to maximum quantity of first product.
My cart store method:
public function store(CartStoreRequest $request) {
$validated = $request->validated();
$product = Product::findOrFail($validated['product_id']);
$rowId = uniqid();
$userID = $validated['user_id'];
// get current user cart
$currentCart = \Cart::session($userID);
if(!empty($currentCart->getContent()->toArray())) {
foreach($currentCart->getContent() as $item) {
$productID = $item->associatedModel->id;
if($productID === $product->id) {
$currentCart->update($item->id, [
'quantity' => [
'relative' => false,
'value' => $product->minStock($item->quantity + $validated['quantity']),
]
]);
} else {
$currentCart->add(array(
'id' => $rowId,
'name' => $product->name,
'price' => $product->price->amount(),
'quantity' => $validated['quantity'],
'associatedModel' => $product,
'attributes' => array(
'first_image' => $product->firstImage,
'formatted_price' => $product->formattedPrice,
'product_stock' => $product->stockCount()
)
));
}
}
} else {
$currentCart->add(array(
'id' => $rowId,
'name' => $product->name,
'price' => $product->price->amount(),
'quantity' => $validated['quantity'],
'associatedModel' => $product,
'attributes' => array(
'first_image' => $product->firstImage,
'formatted_price' => $product->formattedPrice,
'product_stock' => $product->stockCount()
)
));
}
return redirect()->back();
}
I hope that's someone had similar problem and knows how to solve this.
Okay, so the solution is to use product ID as $rowId,
$validated = $request->validated();
$product = Product::findOrFail($validated['product_id']);
$rowId = $product->id;
$userID = $validated['user_id'];
$currentCart = \Cart::session($userID);
$currentCart->add(array(
'id' => $rowId,
'name' => $product->name,
'price' => $product->price->amount(),
'quantity' => $product->minStock($validated['quantity']),
'associatedModel' => $product,
'attributes' => array(
'first_image' => $product->firstImage,
'formatted_price' => $product->formattedPrice,
'product_stock' => $product->stockCount()
)
));
$currentCartContents = $currentCart->get($rowId);
$quantity = $product->minStock($currentCartContents->quantity);
if($currentCartContents->quantity !== $quantity) {
$currentCart->update($rowId, [
'quantity' => [
'relative' => false,
'value' => $quantity,
]
]);
}
return redirect()->back();

How to update a column by joining four tables in laravel

I have four tables
default_products_product_mileage_gap
default_products_mileage_gap
default_products_products
default_products_products_mileage_gaps
I am trying to update a column number_of_products_sold to some value using laravel
What I have tried is:
$qty = 1;
$m = DB::table('products_products')
->join(
'products_products_mileage_gaps',
'products_products.id',
'=',
'products_products_mileage_gaps.entry_id'
)
->join(
'products_product_mileage_gap',
'products_products_mileage_gaps.related_id',
'=',
'products_product_mileage_gap.id'
)
->join(
'products_mileage_gap',
'products_mileage_gap.id',
'=',
'products_product_mileage_gap.mileage_gap_id'
)
->where('products_product_mileage_gap.number_of_products', '>', 0)
->where('products_mileage_gap.name', '=', $mileage_name)
->where('products_products.id', '=', $id)
->update(
array(
'products_product_mileage_gap.number_of_products_sold' => $qty
)
);
Here number_of_products_sold is not updating.
How to update the column
Why you want to add four table together. here is an example to add or update multiple table from by controller.
public function processEmployee(Request $request)
{
$data = $request->all();
$user = User::create([
'name' =>$data['emp_name'],
'email' =>$data['email'],
]);
$emp = Employee::create([
'photo' => $emp_image,
'name' => $data['emp_name'],
'code' => $data['emp_code'],
'status' => $data['emp_status'],
'email' => $data['email'],
'gender' => $data['gender'],
'qualification' => $data['qualification'],
'emergency_number' => $data['emer_number'],
'pan_number' => $data['pan_number'],
'father_name' => $data['father_name'],
'current_address ' => $data['current_address'],
'permanent_address' => $data['permanent_address'],
'formalities' => $data['formalities'],
'offer_acceptance' => $data['offer_acceptance'],
'probation_period' => $data['prob_period'],
'department' => $data['department'],
'salary' => $data['salary'],
'account_number' => $data['account_number'],
'bank_name' => $data['bank_name'],
'ifsc_code' => $data['ifsc_code'],
'pf_account_number' => $data['pf_account_number'],
'un_number' => $data['un_number'],
'pf_status' => $data['pf_status'],
'user_id' => $user->id,
]);
$userRole = UserRole::create([
'role_id' => $data['role'],
'user_id' => $user->id,
]),
]);
if(isset($emp, $user, $userRole)) {
return redirect()->route('employee-manager')
->with('message',
'Employee Successfully Registered.');
}else{
return redirect()->to($this->getRedirectUrl())
->withInput($request->input())->with('error',
'Action Failed Please try again.');
}
}

Non-static method Illuminate\Database\Eloquent\Model::update() should not be called statically

I have a piece of code like this:
<div class="form-group row">
<label for="image" class="col-form-label">Изображение</label>
<input id="image" type="file" class="form-control{{ $errors->has('image') ? ' is-invalid' : '' }}" name="image" value="{{ old('image', $products->image) }}">
#if($products->image)
<img src="{{ Storage::url($products->image) }}" alt="" style="width: 150px">
#endif
#if ($errors->has('image'))
<span class="invalid-feedback"><strong>{{ $errors->first('image') }}</strong></span>
#endif
</div>
I got the following error:
Non-static method Illuminate\Database\Eloquent\Model::update() should
not be called statically
and I have Controller:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|string|max:255',
'image' => 'required|image|mimes:jpg,jpeg,png',
]);
$file = request()->file('image') ? request()->file('image')->store('images', 'public') : null;
$product = product::create([
'name' => $request['name'],
'description' => $request['description'],
'image' => $file,
]);
return redirect()->route('products.index', $product);
}
It's CRUD
public function update(Request $request, $id)
{
$this->validate($request, [ 'key' => 'required|string|max:255', // 'value' => 'required', ]);
$product = product::update([ 'key' => $request['key'], 'name' => $request['name'], // 'value' => $request['value'], ]);
return redirect()->route('products.show', $product);
}
You can use query builder as below...
DB::table('products')->where('id', $id)->update(['value' => $request->value"]);
OR, you may use Eloquent as below...
Product::where('id', $id)->update(['value' => $request->value"]);
Your code should look like below...
public function update(Request $request, $id)
{
$this->validate($request, [ 'key' => 'required|string|max:255', // 'value' => 'required', ]);
$product = product::where('id', $id)->update([ 'key' => $request['key'], 'name' => $request['name'], // 'value' => $request['value'], ]);
return redirect()->route('products.show', $product);
}
Change Line:
$product = product::update([ 'key' => $request['key'], 'name' => $request['name'], // 'value' => $request['value'], ]);
Change Line To: here 'product' will be table name
DB::table('product')->update([ 'key' => $request['key'], 'name' => $request['name']]);
I suggest you to change your approach to update data. In order to update your data with Laravel or add where it will be help
convert this:
product::update([ 'key' => $request['key'],'name' => $request['name']);
to:
product::where('id',$id)->update([ 'key' => $request['key'],'name' => $request['name']);
or:
product::find($id)->update([ 'key' => $request['key'],'name' => $request['name']);
Change line
$product = product::update([ 'key' => $request['key'], 'name' => $request['name'], // 'value' => $request['value'], ]);
To
$product = (new product)->update([ 'key' => $request['key'], 'name' => $request['name'], // 'value' => $request['value'], ]);
Note: It is always advisable to follow the Laravel convention. So
Product instead of product would be better for the model name. However, use the exact case of the class name. Your model file wasn't posted but since your store method worked fine, I believe you used product instead of Product
You should try this:
{
$this->validate($request, [
'name' => 'required|string|max:255',
'image' => 'required|image|mimes:jpg,jpeg,png',
]);
$file = request()->file('image') ? request()->file('image')->store('images', 'public') : null;
$product = product::create([
'name' => $request['name'],
'description' => $request['description'],
'image' => $file,
]);
return redirect()->route('products.index');
}
I suggest you to change your approach to update data. In order to update your data with Laravel (in fact, not only Laravel but in generally all programming languages and query such as MySQL), you need to determine what record you want to update. In Laravel you can do that with find method. Sure, you can use another method like WHERE. So, for answer your problem, you can't do an update like to create. Therefore, your update method code should look like this:
public function update(Request $request, $id)
{
$this->validate($request, [
'key' => 'required|string|max:255',
// 'value' => 'required',
]);
$product = Product::find($id); //get the object of product you want to update
$product->key = $request['key'];
$product->name = $request['name'];
//$product->value = $request['value'];
$product->save();
return redirect()->route('products.show', $product);
}
I asume you come from an update form, make sure your form's action is dynamic
<form action="{{ route ('products') }}/{{ $product->id }}" method="post">
#csrf
#method('PATCH')

laravel undefined variable: itinerary

I can't seem to find the variable itinerary from my update function in my controller. What seems to be the problem for this?
Error says: Undefined variable: itinerary (View: C:\xampp\htdocs\project_name\resources\views\Agent\edit.blade.php)
AgentsController update function
public function update(Request $request, $p_id){
$this->validate($request, [
'packageName' => 'required',
'adultPrice' => 'required',
'childPrice' => 'required',
'infantPrice' => 'required',
'excessPrice' => 'required',
'type' => 'required',
'inclusions' => 'required',
'additionalInfo' => 'required',
'reminders' => 'required',
'photo' => 'required',
'tags' => 'required',
'noOfDays' => 'required',
'day' => 'required',
'time' => 'required',
'destination' => 'required'
]);
$packages = Packages::find($p_id);
$packages->packageName = $request->input('packageName');
$packages->adultPrice = $request->input('adultPrice');
$packages->childPrice = $request->input('childPrice');
$packages->infantPrice = $request->input('infantPrice');
$packages->excessPrice = $request->input('excessPrice');
$packages->type = $request->input('type');
$packages->inclusions = $request->input('inclusions');
$packages->additionalInfo = $request->input('additionalInfo');
$packages->reminders = $request->input('reminders');
$packages->photo = $request->input('photo');
$packages->tags = $request->input('tags');
$packages->save();
$itinerary = Itinerary::find($p_id);
if($itinerary->p_id == $packages->p_id){
$itinerary->noOfDays = $request->input('noOfDays');
$itinerary->day = $request->input('day');
$itinerary->time = $request->input('time');
$itinerary->destination = $request->input('destination');
$itinerary->save();
return redirect('Agent/Packages')->with('success', 'Updated');
}
}
edit.blade.php where the error is located
{{!!Form::open(array('class' => 'form-horizontal', 'method' => 'post', 'action' => array('AgentsController#update', $packages->p_id, $itinerary->p_id)))!!}}
Itinerary.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Itinerary extends Model{
public $fillable = [
'p_id',
'noOfDays',
'day',
'time',
'destination'
];
protected $primaryKey = 'i_id';
}
?>
Edit function
public function edit($p_id){
$packages = Packages::find($p_id);
$itinerary = Itinerary::find($p_id);
return View::make('\Agent\Edit', ['packages' => $packages, 'itineraries' => $itinerary]);
}
The way you pass the data is wrong.
Documentation
There are few ways you can pass. Examples :
1 -
return View::make('Agent.edit', ['packages' => $packages, 'itinerary' => $itinerary]);
2 - return View::make('Agent.edit')->with(['packages' => $packages, 'itinerary' => $itinerary]);
3 - return View::make('Agent.edit')->with('packages', $packages)->with('itinerary', $itinerary);
In your edit.blade.php, try remplacing your $itinerary variable by $itineraries (plural).

Categories