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
}
Related
In making output in my blade view in laravel it does not output all data gathered from database. Is there any wrong in my code? I it shows only some of my data from laravel but not all shows.
Admin View as you can see here its upto page 9
User View as you can see here there is only 4 pages
User Controller (Problem in showing data from database):
Here is my problem in this controller
$this->middleware('auth');
}
public function shareLinks()
{
$user = Auth::user();
$settings = Settings::first();
$ad_limit = $user->membership->ad_limit;
$membership = $user->membership->id;
$ad = Share::whereUser_id($user->id)->where('date','=',date('Y-m-d'))->count();
if ($ad == 0)
{
$ptcse = Link::whereMembership_id($membership)->take($ad_limit)->whereStatus(1)->count();
if ($ptcse == 0){
session()->flash('message', 'Sorry To Say You That Currently there is no Cash Links for you. Please wait or upgrade your membership, ');
Session::flash('type', 'error');
Session::flash('title', 'Error');
return redirect()->route('userMemberships');
}
else {
$ptcs = Link::whereMembership_id($membership)->take($ad_limit)->whereStatus(1)->get();
foreach ($ptcs as $ptc)
{
$info =([
'user_id'=> $user->id,
'date'=> date('Y-m-d'),
'link_id'=> $ptc->id,
]);
Share::create($info);
}
$adverts = Share::whereUser_id($user->id)->where('date','=',date('Y-m-d'))->paginate(10);
return view('user.viewads.share',compact('adverts','settings'));
}
}else{
$adverts = Share::whereUser_id($user->id)->where('date','=',date('Y-m-d'))->paginate(10);
return view('user.viewads.share',compact('adverts','settings'));
}
}
public function save_share($id) {
$user = Auth::user();
$advert= Share::findOrFail($id);
if ($advert-> status == 1){
session()->flash('message', 'This task has been already completed.');
Session::flash('type', 'warning');
Session::flash('title', 'Un-Successful');
return redirect()->route('userLink.share');
}
$advert->status = 1;
$advert->save();
$rewards = $advert->link->rewards;
$profile = $user->profile;
$profile->main_balance = $profile->main_balance + $rewards;
$profile->save();
$log = UserLog::create([
'user_id' => $user->id,
'reference' => str_random(12),
'type' => 1,
'for' => 'Cash Links',
'from' => 'Self',
'details'=>'You receive a reward for completing a task.',
'amount'=>$rewards,
]);
$upliner = Referral::whereUser_id($user->id)->count();
if ($upliner == 1){
$settings = Settings::first();
$referral = Referral::whereUser_id($user->id)->first();
$upliner = $referral->reflink->user->profile;
$percentage = $settings->referral_advert;
$commission = (($percentage / 100) * $rewards);
$upliner->referral_balance = $upliner->referral_balance + $commission;
$upliner->save();
$referral->total = $referral->total + $commission;
$referral->today = $referral->today + $commission;
$referral->save();
$log = UserLog::create([
'user_id' => $referral->reflink->user->id,
'reference' => str_random(12),
'for' => 'Referral',
'type' => 2,
'from' => $user->name,
'details'=>'You receive a referral bonus.',
'amount'=>$commission,
]);
}
session()->flash('message', 'This task has been successfully completed.');
Session::flash('type', 'success');
Session::flash('title', 'Success');
$robi = "success";
return response()->json(array('robi'=>$robi), 200);
}
public function cashLinks()
{
$user = Auth::user();
$settings = Settings::first();
$ad_limit = $user->membership->ad_limit;
$membership = $user->membership->id;
$ad = Advert::whereUser_id($user->id)->where('date','=',date('Y-m-d'))->count();
if ($ad == 0)
{
$ptcse = Ptc::whereMembership_id($membership)->take($ad_limit)->whereStatus(1)->count();
if ($ptcse == 0){
session()->flash('message', 'Sorry To Say You That Currently there is no Cash Links for you. Please wait or upgrade your membership, ');
Session::flash('type', 'error');
Session::flash('title', 'Error');
return redirect()->route('userMemberships');
}
else {
$ptcs = Ptc::whereMembership_id($membership)->take($ad_limit)->whereStatus(1)->get();
foreach ($ptcs as $ptc)
{
$info =([
'user_id'=> $user->id,
'date'=> date('Y-m-d'),
'ptc_id'=> $ptc->id,
]);
Advert::create($info);
}
$adverts = Advert::whereUser_id($user->id)->where('date','=',date('Y-m-d'))->paginate(10);
return view('user.viewads.index',compact('adverts','settings'));
}
}else{
$adverts = Advert::whereUser_id($user->id)->where('date','=',date('Y-m-d'))->paginate(10);
return view('user.viewads.index',compact('adverts','settings'));
}
}
public function cashLinkConfirm($id)
{
$user = Auth::user();
$advert= Advert::findOrFail($id);
if ($advert-> status == 1){
session()->flash('message', 'This task has been already completed.');
Session::flash('type', 'warning');
Session::flash('title', 'Un-Successful');
return redirect()->route('userCash.links');
}
if ($advert->ptc->type == 2){
$advert->ptc->order->totalhit = $advert->ptc->order->totalhit +1;
$advert->ptc->order->save();
}
$advert->status = 1;
$advert->save();
$advert->ptc->count = $advert->ptc->count + 1;
$advert->ptc->save();
$rewards = $advert->ptc->rewards;
$profile = $user->profile;
$profile->main_balance = $profile->main_balance + $rewards;
$profile->save();
$log = UserLog::create([
'user_id' => $user->id,
'reference' => str_random(12),
'type' => 1,
'for' => 'Cash Links',
'from' => 'Self',
'details'=>'You receive a reward for completing a task.',
'amount'=>$rewards,
]);
$upliner = Referral::whereUser_id($user->id)->count();
if ($upliner == 1){
$settings = Settings::first();
$referral = Referral::whereUser_id($user->id)->first();
$upliner = $referral->reflink->user->profile;
$percentage = $settings->referral_advert;
$commission = (($percentage / 100) * $rewards);
$upliner->referral_balance = $upliner->referral_balance + $commission;
$upliner->save();
$referral->total = $referral->total + $commission;
$referral->today = $referral->today + $commission;
$referral->save();
$log = UserLog::create([
'user_id' => $referral->reflink->user->id,
'reference' => str_random(12),
'for' => 'Referral',
'type' => 2,
'from' => $user->name,
'details'=>'You receive a referrral bonus.',
'amount'=>$commission,
]);
}
session()->flash('message', 'This task has been successfully completed.');
Session::flash('type', 'success');
Session::flash('title', 'Success');
return redirect()->route('userCash.links');
}
public function cashLinkShow($id)
{
$advert= Advert::findOrFail($id);
if ($advert->ptc->status == 0){
$advert->status = 1;
$advert->save();
session()->flash('message', 'This task has expired.');
Session::flash('type', 'warning');
Session::flash('title', 'Un-Successful');
return redirect()->route('userCash.links');
}
if ($advert->ptc->hit == $advert->ptc->count){
$advert->ptc->status = 2;
$advert->ptc->save();
if ($advert->ptc->type == 2){
$advert->ptc->order->status = 2;
$advert->ptc->order->save();
}
$advert->status = 1;
$advert->save();
session()->flash('message', 'This task has expired or traffic limit reached. You will not get any reward.');
Session::flash('type', 'warning');
Session::flash('title', 'Un-Successful');
return redirect()->route('userCash.links');
}
return view('user.viewads.showads', compact('advert'));
}
public function cashVideoConfirm($id)
{
$user = Auth::user();
$video= Video::findOrFail($id);
if ($video-> status == 1){
session()->flash('message', 'This task has been already completed.');
Session::flash('type', 'warning');
Session::flash('title', 'Un-Successful');
return redirect()->route('userCash.videos');
}
$video->status = 1;
$video->save();
$rewards = $video->ppv->rewards;
$profile = $user->profile;
$profile->main_balance = $profile->main_balance + $rewards;
$profile->save();
$log = UserLog::create([
'user_id' => $user->id,
'reference' => str_random(12),
'for' => 'Cash Video',
'type' => 1,
'from' => 'Self',
'details'=>'You receive a reward for completing a task.',
'amount'=>$rewards,
]);
$upliner = Referral::whereUser_id($user->id)->count();
if ($upliner == 1){
$settings = Settings::first();
$referral = Referral::whereUser_id($user->id)->first();
$upliner = $referral->reflink->user->profile;
$percentage = $settings->referral_advert;
$commission = (($percentage / 100) * $rewards);
$upliner->referral_balance = $upliner->referral_balance + $commission;
$upliner->save();
$referral->total = $referral->total + $commission;
$referral->today = $referral->today + $commission;
$referral->save();
$log = UserLog::create([
'user_id' => $referral->reflink->user->id,
'reference' => str_random(12),
'for' => 'Referral',
'type' => 2,
'from' => $user->name,
'details'=>'You receive a referral bonus.',
'amount'=>$commission,
]);
}
session()->flash('message', 'This task has been successfully completed.');
Session::flash('type', 'success');
Session::flash('title', 'Success');
return redirect()->route('userCash.videos');
}
public function cashVideoShow($id)
{
$video= Video::findOrFail($id);
return view('user.viewads.vshow', compact('video'));
}
public function cashVideos()
{
$user = Auth::user();
$settings = Settings::first();
$ad_limit = $user->membership->ad_limit;
$membership = $user->membership->id;
$ad = Video::whereUser_id($user->id)->where('date','=',date('Y-m-d'))->count();
if ($ad == 0)
{
$ppvse = Ppv::whereMembership_id($membership)->take($ad_limit)->whereStatus(1)->count();
if ($ppvse == 0){
session()->flash('message', 'Sorry To Say You That Currently there is no Cash Videos for you. Please wait or upgrade your membership, ');
Session::flash('type', 'error');
Session::flash('title', 'Error');
return redirect()->route('userMemberships');
}
else {
$ppvs = Ppv::whereMembership_id($membership)->take($ad_limit)->whereStatus(1)->get();
foreach ($ppvs as $ppv)
{
$info =([
'user_id'=> $user->id,
'date'=> date('Y-m-d'),
'ppv_id'=> $ppv->id,
]);
Video::create($info);
}
$videos = Video::whereUser_id($user->id)->where('date','=',date('Y-m-d'))->paginate(10);
return view('user.viewads.vindex',compact('videos','settings'));
}
}else{
$videos = Video::whereUser_id($user->id)->where('date','=',date('Y-m-d'))->paginate(10);
return view('user.viewads.vindex',compact('videos','settings'));
}
}
Admin Preview Controller:
return view('admin.paidtoclick.index', compact('advertisements'));
}
public function preview($id)
{
$log = Ptc::findOrFail($id);
return view('admin.paidtoclick.preview', compact('log'));
}
In my laravel application, I'm trying to update some content using the following controller function. But every time when I try to run the following function am getting an error
public function update_tcp(Request $request, $id)
{
try{
Session::put('tcpSession', '1');
$request->merge(['gender' => 'M']);
$this->validate($request, [
'first_name_tcp2' => 'required',
'last_name_tcp2' => 'required',
'image_id' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'user_id'=>'required',
'gender'=>'required',
'date_of_birth_tcp2'=>'required'
]);
//$input = $request->except('_method', '_token');
$input = $request->all();
unset($input['_token']);
unset($input['_method']);
if ($image = $request->file('image_id')) {
$destinationPath = 'propics/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image_id'] = "$profileImage";
//dd($profileImage);
}else{
//unset($input['image']);
$profileImage='default-avatar.png';
$request->merge(['image_id' => 'default-avatar.png']);
}
$data = $request->input();
$tcp = TakeCarePerson::WHERE('id','=',''.$id.'');
$tcp->first_name = $data['first_name_tcp2'];
$tcp->last_name = $data['last_name_tcp2'];
$tcp->date_of_birth = $data['date_of_birth_tcp2'];
$tcp->user_id = $data['user_id'];
$tcp->image_id = $profileImage;
$tcp->gender= $data['gender'];
$tcp->update();
return redirect()->route('participants.index')
->with('success',__('texts.Take care person updated successfully.'));
} catch(Exception $e){
return back() ->with('failedTcp',__('texts.Le fichier sélectionné doit être une image.'));
}
}
This is the error,
ArgumentCountError Too few arguments to function
Illuminate\Database\Eloquent\Builder::update(), 0 passed
Where do I need to fix in order to function my update function properly?
You are not passing data to update .Instead where find by id and then call save()
$tcp = TakeCarePerson::find($id);
$tcp->first_name = $data['first_name_tcp2'];
$tcp->last_name = $data['last_name_tcp2'];
$tcp->date_of_birth = $data['date_of_birth_tcp2'];
$tcp->user_id = $data['user_id'];
$tcp->image_id = $profileImage;
$tcp->gender= $data['gender'];
$tcp->save();
or
$tcp = TakeCarePerson::where('id','=',$id)->update([
'first_name'=> $data['first_name_tcp2'],
'last_name'=>$data['last_name_tcp2'],
'date_of_birth'=>$data['date_of_birth_tcp2'],
'user_id'=>$data['user_id'],
'image_id'=>$profileImage,
'gender'=>$data['gender']
]);
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.
From the model TagModel i can filter the value which i want it, but value is stored in the form of object variable. To play with those data in controller i am not able to pluck the particular id.
This is my model
public static function getLatestTag($name){
return $tagIds =DB::table('tags')
->where ('is_deleted',0)
->where('name',$name)
->get();
}
This is my controller code:
foreach ($newTags as $newTag) {
$productTagIds[] = TagModel::getLatestTag($newTag);
dd($id);
}
$productId = (int)ProductManagementModel::getMaxId();
foreach ($productTagIds as $productTagId) {
$productTag = new ProductTagModel;
$productTag ->product_id = $productId;
$productTag ->tag_id = $productTagId;
$productTag->save();
}
the value which i want is stored in the variable $productTagIds which is object variable. How can I pluck just id from this?
public function addProduct()
{
foreach(Input::get('tagName') as $checkTag){
$newTags[]=$checkTag;
}
foreach ($newTags as $newTag) {
if(TagModel::checkExist($newTag)){
$tagExist[] = TagModel::checkExist($newTag);
$message = 'The tag <b>'.$checkTag.'</b> already exist';
Session::flash('class', 'alert alert-error');
Session::flash('message', $message);
return View::make('admin.product_management.add');
}
else {
$objectTagProduct = new TagModel;
$objectTagProduct ->name = $newTag;
$objectTagProduct->save();
$productTagIds[]=$objectTagProduct->id;
}
}
$objectProduct = new ProductManagementModel;
$objectProduct->product_name = Input::get('product_name');
$objectProduct->product_url = $productUrl;
$objectProduct->category_id = Input::get('category_id');
$objectProduct->product_cost = Input::get('product_cost');
$objectProduct->product_short_description = Input::get('product_short_description');
$objectProduct->product_description = Input::get('product_description');
$objectProduct->is_active = Input::get('is_active');
$objectProduct->created_at = Auth::user()->id;
$objectProduct->updated_at = Auth::user()->id;
if($logo != '')
{
$objectProduct->product_attachment = $logo;
}
$objectProduct->save();
$productId = (int)ProductManagementModel::getMaxId();
//dd($productId);
foreach ($productTagIds as $productTagId) {
//dd($productTagIds);
$productTag = new ProductTagModel;
$productTag ->product_id = $productId;
$productTag ->tag_id = $productTagId;
$productTag->save();
}
if($objectProduct->id) {
Session::flash('class', 'alert alert-success');
Session::flash('message', 'Product successfully added');
return View::make('admin.product_management.add');
} else {
Session::flash('class', 'alert alert-error');
Session::flash('message', 'Something error');
return View::make('admin.product_management.add');
}
}
The code might flash a certain error that have to troubleshoot by yourself. I have kept
$productTagIds[]=$objectTagProduct->id;
after $objectTagProduct->save(); please try it
public static function getLatestTag($name){
return $tagIds = DB::table('tags')
->where ('is_deleted',0)
->where('name',$name)
->pluck(id);
}
public static function getLatestTag($name){
return App\TagModel::where('is_deleted',0)->where('name',$name)->first()->id;
}
$ids = [];
foreach ($newTags as $newTag) {
$productTagId = TagModel::getLatestTag($newTag);
array_push($ids,$productTagId);
}
$productId = (int)ProductManagementModel::getMaxId();
foreach ($ids as $productTagId) {
$productTag = new ProductTagModel;
$productTag ->product_id = $productId;
$productTag ->tag_id = $productTagId;
$productTag->save();
}
try to use eloquent like this
to get the particular value from the object class variable
$productTagIds[]=$objectTagProduct->id;`
public function addProduct()
{
foreach(Input::get('tagName') as $checkTag){
$newTags[]=$checkTag;
}
foreach ($newTags as $newTag) {
if(TagModel::checkExist($newTag)){
$tagExist[] = TagModel::checkExist($newTag);
$message = 'The tag <b>'.$checkTag.'</b> already exist';
Session::flash('class', 'alert alert-error');
Session::flash('message', $message);
return View::make('admin.product_management.add');
}
else {
$objectTagProduct = new TagModel;
$objectTagProduct ->name = $newTag;
$objectTagProduct->save();
}
}
$objectProduct = new ProductManagementModel;
$objectProduct->product_name = Input::get('product_name');
$objectProduct->product_url = $productUrl;
$objectProduct->category_id = Input::get('category_id');
$objectProduct->product_cost = Input::get('product_cost');
$objectProduct->product_short_description = Input::get('product_short_description');
$objectProduct->product_description = Input::get('product_description');
$objectProduct->is_active = Input::get('is_active');
$objectProduct->created_at = Auth::user()->id;
$objectProduct->updated_at = Auth::user()->id;
if($logo != '')
{
$objectProduct->product_attachment = $logo;
}
$objectProduct->save();
$productId = (int)ProductManagementModel::getMaxId();
//dd($productId);
foreach ($productTagIds as $productTagId) {
//dd($productTagIds);
$productTag = new ProductTagModel;
$productTag ->product_id = $productId;
$productTag ->tag_id = $productTagId;
$productTagIds[]=$objectTagProduct->id;
$productTag->save();
}
if($objectProduct->id) {
Session::flash('class', 'alert alert-success');
Session::flash('message', 'Product successfully added');
return View::make('admin.product_management.add');
} else {
Session::flash('class', 'alert alert-error');
Session::flash('message', 'Something error');
return View::make('admin.product_management.add');
}
}
I came to knew that to get the data from object class variable $productTagIds[]=$objectTagProduct->id;
But i am confused with its flow and where to execute this code.
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}"); */
}