Run some calculation and then update data in Laravel 5.2 - php

Here is a very simple store method of a product controller. I do some calculation and then store the data into the database. But while updating data I have to run this calculations again and then have to save the data.
I tried several ways but I get nothing but error messages as I'm new in Laravel. How can I write the proper update method?
public function store(Request $request)
{
//vat and profit calculations
$vat = $request->vat;
$buying_price = $request->buying_price;
$selling_price = $request->selling_price;
$total_price = $buying_price+($buying_price*$vat/100);
$profit = $selling_price-$total_price;
$product = Products::create([
'product_name' => $request->product_name,
'buying_price' => $request->buying_price,
'selling_price' => $request->selling_price,
'vat' => $request->vat,
'total_price' => $total_price,
'profit' => $profit,
]);
return redirect("Product/{$product->id}");
}
Update method (which is not working as I expect):
public function update(Request $request, $id)
{
$vat = $request->vat;
$buying_price = $request->buying_price;
$selling_price = $request->selling_price;
$total_price = $buying_price+($buying_price*$vat/100);
$profit = $selling_price-$total_price;
$product = Products::findOrFail($id);
$product = Products::update([
'product_name' => $request->product_name,
'buying_price' => $request->buying_price,
'selling_price' => $request->selling_price,
'vat' => $request->vat,
'total_price' => $total_price,
'profit' => $profit,
]);
return redirect("Product/{$product->id}");
/* Basic update system but this does not update the total_price and profit column
$input = $request->all();
$product = Products::findOrFail($id);
$product->update($input);
return redirect("Product/{$product->id}"); */
}

Should be like this ...
public function update(Request $request, $id){
$vat = $request->vat;
$buying_price = $request->buying_price;
$selling_price = $request->selling_price;
$total_price = $buying_price+($buying_price*$vat/100);
$profit = $selling_price-$total_price;
$product = Products::findOrFail($id);
$product->product_name = $request->product_name;
$product->product_category_id = $request->product_category_id;
$product->product_type_id = $request->product_type_id;
$product->product_description = $request->product_description;
$product->product_weight = $request->product_weight;
$product->buying_price = $request->buying_price;
$product->selling_price = $request->selling_price;
$product->vat = $request->vat;
$product->total_price = $total_price;
$product->profit = $profit;
$product->in_stock = $request->in_stock;
$updated_product = $product->save();
if(isset($updated_product) && $updated_product != '') {
return redirect("Product/".$id);
}
}

Please Try This.
public function update(Request $request, $id)
{
$vat = $request->vat;
$buying_price = $request->buying_price;
$selling_price = $request->selling_price;
$total_price = $buying_price+($buying_price*$vat/100);
$profit = $selling_price-$total_price;
$product = Product::where('id', $id)->first();
$product->product_name = $request->product_name;
$product->buying_price = $request->buying_price;
$product->selling_price = $request->selling_price;
$product->vat = $request->vat;
$product->total_price = $total_price;
$product->profit = $profit;
$product->save();
return redirect("Product/{$product->id}");
/* Basic update system but this does not update the total_price and profit column
$input = $request->all();
$product = Products::findOrFail($id);
$product->update($input);
return redirect("Product/{$product->id}"); */
}

Related

Update query laravel return false result and nothing error show why?

i'm working with laravel project, and i have an issue that is update query result return false value if i update with the same data, how to solve this? do i have to validate first before run the query and send a notification that the data is the same?
well this is my codes
public function update(Request $request)
{
$kamar_id = $request->input('kamar_id');
$title = $request->input('title');
$content = $request->input('content');
$keyword = $request->input('keyword');
$description = $request->input('description');
$prolog = $request->input('prolog');
$path = $request->input('path');
$sort = $request->input('sort');
$status = $request->input('status');
$type = $request->input('type');
$user_id = $request->input('user_id');
if (empty($request->input('path'))) {
$path = serialize(array('data/def.png'));
}else{
$path = serialize(explode(',', $request->input('path')));
}
$data = array('title' => $title,
'content' => $content,
'keyword' => $keyword,
'description' => $description,
'prolog' => $prolog,
'path' => $path,
'sort' => $sort,
'status' => $status,
'type' => $type,
'user_id' => $user_id);
// echo($kamar_id);
$update = Kamar::where('kamar_id',$kamar_id)->update($data);
if ($update) {
$response['status'] = 1;
}else{
$response['status'] = 0;
}
return response()->json($response);
}
thanks for helping me
Laravel Eloquent Update method returns true if anything updated in database from your query and return false if nothing is updated in database from your query.
refer:
https://laravel.com/docs/5.8/eloquent#updates
!nullTry
$update = Kamar::where('kamar_id','=',$kamar_id)->first();
if (!null($update))
{
$update->title = $title;
$update->content = $content;
$update->keyword = $keyword;
$update->description = $description;
$update->prolog = $prolog;
$update->path = $path;
$update->sort = $sort;
$update->status = $status;
$update->type = $type;
$update->user_id = $user_id;
$update->save();
$response['status'] = 1;
}
else
{
$response['status'] = 0;
}
Try using this
$kamarObj = new Kamar();
$kamarData = $kamarObj->find($kamar_id);
$result = $kamarData->update($data);
You can force updated_at column to be updated (or you can create this column if you don't have). So the query will be always updated.

How to replicate in php

I'm trying to create a function that will replicate/clone/duplicate a product including all it's properties and it's shipping options.
However, I succeeded to duplicate the product but the shipping options are not replicated. See my codes below;
Any help will be highly appreciated
Thanks
public function CreateProductPost(Request $request){
if (Auth::user()->vendor == false) {
return redirect()->route('profile');
}
if ($request->name == null) {
session()->flash('errormessage','Product name is required');
return redirect()->back()->withInput();
}
if (mb_strlen($request->name) > 60) {
session()->flash('errormessage','Product name cannot be longer than 60 characters.');
return redirect()->back()->withInput();
}
if ($request->category_id == null) {
session()->flash('errormessage','Product category is required');
$shippingoptions[] = $opt;
}
}
$product = new Product;
$product->name = $request->name;
$product->uniqueid = random_int(10000, 99999);
$product->category_id = $category->id;
$product->description = $request->description;
$product->refund_policy = $request->refund_policy;
$product->fromc = $request->fromc;
$product->tocount = $request->tocount;
$product->price = $request->price;
$product->currency = $request->currency;
$product->inventory = $request->inventory;
if ($request->image !== null) {
$product->image = $request->image->store('uploads','public');
}
$product->buyout = 0;
$product->fe = $fe;
$product->seller_id = Auth::user()->id;
$product->save();
foreach ($shippingoptions as $opt) {
$so = new ShippingOption();
$so->product_id = $product->id;
$so->desc = $opt['desc'];
$so->days = $opt['days'];
$so->price = $opt['price'];
$so->save();
}
session()->flash('successmessage','Product successfully created');
return redirect()->route('products');
}
function DuplicateProductPost($uniqueid, Request $request){
$product = Product::where('uniqueid',$uniqueid)->first();
if ($product == null) {
return redirect()->route('products');
}
if (Auth::user()->id !== $product->seller->id) {
return redirect()->route('products');
}
$newProduct = $product->replicate();
$newProduct->uniqueid = random_int(10000, 99999);
$newProduct->save();
session()->flash('successmessage','Product successfully duplicated');
return redirect()->route('products');
}
Any help will be highly appreciated
Thanks
You need to replicate both your Product and ShippingOption models, so use the following logic:
$product = Product::where('uniqueid',$uniqueid)->first();
...
$newProduct = $product->replicate();
$newProduct->uniqueid = random_int(10000, 99999);
$newProduct->save();
foreach($product->shippingOptions AS $shippingOption){
$newShippingOption = $shippingOption->replicate();
$newShippingOption->product_id = $newProduct->id;
$newShippingOption->save();
}
Note, you need to have a relationship between Product and ShippingOption, otherwise you will need to manually query for them:
$oldShippingOptions = ShippingOption::where("product_id", "=", $product->id)->get();
foreach($oldShippingOptions AS $shippingOption){
...
}
The ->replicate() method does not clone all related records, as that might not be the intended requirement, so you need to do it manually.

"Trying to get property 'price' of non-object"

I had a Laravel script installed, Now When the user fills in the new order form and makes an order for ordering, will be displayed:
"Trying to get property 'price' of non-object"
The error is for usercontroller and this line:
" $price = ($request->quantity * $servicePrice->price) / 1000;"
This part code is for new order in usercontroller:
public function newOrder()
{
$categories = Category::where('status', 1)->orderBy('name')->get();
return view('user.newOrder', compact('categories'));
}
public function getPack(Request $request)
{
$items = Service::where('category_id', $request->id)->where('status', 1)->orderBy('name')->get();
return $items;
}
public function getPackDetails(Request $request)
{
$items = Service::findOrFail($request->id);
return $items;
}
public function storeNewOrder(Request $request)
{
$this->validate($request, [
'category' => 'required',
'service' => 'required',
'link' => 'required',
'quantity' => 'required',
]);
$service = Service::where('category_id', $request->category)->where('id', $request->service)->first();
$servicePrice = ServicePrice::where('category_id', $request->category)->where('service_id', $request->service)->where('user_id', Auth::id())->first();
$item = new Order();
$user = User::findOrFail(Auth::id());
$transaction = new Transaction();
if ($request->quantity >= $service->min && $request->quantity <= $service->max) {
$price = ($request->quantity * $servicePrice->price) / 1000;
if ($user->balance >= $price) {
$item->category_id = $request->category;
$item->service_id = $request->service;
$item->user_id = Auth::id();
$item->service_no = $service->service_id;
$item->order_no = 0;
$item->link = $request->link;
$item->quantity = $request->quantity;
$item->price = $price;
$item->status = 'Pending';
$item->start_counter = 0;
$item->remains = $request->quantity;
$item->order_through = 'Web';
$item->save();
$user->balance = $user->balance - $price;
$user->save();
$transaction->user_id = Auth::id();
$transaction->amount = $price;
$transaction->user_balance = $user->balance;
$transaction->type = 1;
$transaction->trx = str_random(12);
$transaction->save();
send_email($user->email, $user->name, 'Order Placed Successfully', 'Your ' . $request->quantity . ' ' . $service->name . ' has been placed successfully.');
session()->flash('success', 'Order request send successfully');
return back();
} else {
session()->flash('alert', 'Insufficient Balance');
return back();
}
} else {
session()->flash('alert', 'Quantity should be within ' .
$service->min . ' to ' . $service->max);
return back();
}
}
Most probably the problem comes from this line:
$servicePrice = ServicePrice::where('category_id', $request->category)->where('service_id', $request->service)->where('user_id', Auth::id())->first();
If a query does not return any result from the database, the code will return null.
A good practice is to check if the result is null and you should handle it.
That means, before you use the $servicePrice, you need to check if it contains anything:
if(!$servicePrice){ //same result: if($servicePrice == null) {
//`$servicePrice==null`, so you should handle the error here - throw an exception or return
}
//your code here
$servicePrice = ServicePrice::where('category_id', $request->category)->where('service_id', $request->service)->where('user_id', Auth::id())->first();
Also, the authenticated user can be retrieved directly from:
$user = Auth::user();
If the visitor is not authenticated, $user will be null, for the same reason than the previous.
if(!$user){
//the user is NOT authenticated
} else {
//the user is authenticated
}

I want to replicate one row into 365 row in one table in Laravel

I want to save the same data with 365 records within one table. I'm new to Laravel.
I've tried with replicate() but was unsuccessful. I tried this on the Apache server and used Laravel5.7.
my controller
public function price_save(Request $request) {
$price=new Price();
$price->price=$request->price;
$price->extra_bed=$request->extra_bed;
$price->room_id=$request->room;
$id=$request->room;
$price = Price::find($id);
if(null !== $price){
$new = $price->replicate();
if(null !== $new){
$new->push();
// $price->save();
}
I am NOT sure about your code, But you can customize it as per your needs, To just get idea :
$model = User::find($id);
$model->load('invoices');
$newModel = $model->replicate();
$newModel->push();
foreach($model->getRelations() as $relation => $items){
foreach($items as $item){
unset($item->id);
$newModel->{$relation}()->create($item->toArray());
}
}
Credits
public function price_save(Request $request, int $id)
{
if ($id > 365) {
return;
}
$price = new Price();
$price->price = $request->price;
$price->extra_bed = $request->extra_bed;
$price->room_id = $request->room;
$price->save();
$existing = Price::find($request->room);
if ($existing) {
$request = $request->replace([
'price' => $price->price,
'extra_bed' => $price->extra_bed,
'room_id' => $price->room,
]);
}
return price_save($request, $id++);
}

Laravel insert data twice when timeout occurs

I noticed laravel re-preform the insertion action when the timeout occurs
How can I shop it from retiring to insert the data again when timeout error fires ?
loop
foreach ($comments_data as $comment_data)
{
if ( ! empty($comment_data['date']))
{
$total_rating[] = $this->check_rating_value($comment_data['rating']);
$comment_id = ( new Comment() )->saveComments($shop, $comment_data, $product_id, $urls, $shop_options);
( new Comments_images() )->save_images($comment_id, $shop, $comment_data['images']);
}
}
inserting code
public function saveComments($shop, $comments_data, $product_id, $url, $shop_options)
{
$date = Carbon::parse($comments_data['date']);
if ($shop_options->filter_status == 1)
{
$comments = str_replace(explode(',', $shop_options->filter_find_words), explode(',', $shop_options->filter_alter_words), $comments_data['comment']);
} else
{
$comments = $comments_data['comment'];
}
$faker = Factory::create();
$this->shop_name = $shop;
$this->comment = $comments;
$this->rating = $this->check_rating_value($comments_data['rating']);
$this->product_id = $product_id;
$this->user_name = $faker->userName;
$this->product_url = $url;
$this->created_at = $date->toDateTimeString();
$this->country = $comments_data['country'] == 'IL' ? 'PS' : $comments_data['country'];
$this->view = 1;
$this->save();
return $this->id;
}

Categories