How to update database base on laravel checkbox value - php

I load check boxes from database with they are checked or not,
<div class="row">
<div class="col-xs-12">
<div class="form-group">
#php
$json = $orders->data;
$json = json_decode($json, true);
$products = $json['order_info']['products'];
$data = '';
foreach ($products as $hitsIndex => $hitsValue) {
$data .= $hitsValue['type']. ', ';
}
$data = rtrim($data, ', ');
$agosProducts = Utility::constant('agos_products1');
#endphp
{{Html::validation($orders, 'product')}}
<label for="products" class="control-label">{{Translator::transSmart('app.Products', 'Products')}}</label><br><br>
#foreach($agosProducts as $product)
<label class="control-label "for="{{ $product['type'] }}">
<input id="{{ $product['type'] }}" name="{{ $product['type'] }}" type="checkbox" value="{{ $product['type'] }}"
#foreach ($products as $hitsIndex => $hitsValue)
#if(in_array($hitsValue['type'], $product)) checked=checked #endif
#endforeach
>
{{ $product['name'] }}
</label>
<br>
#endforeach
</div>
</div>
</div>
Now i want to update my database base on checkbox value.
For example if say i load checkbox 1 as checked from database and now it's unchecked i need to update it in database.
This code i can get all the current status of checkbox but i don't know previous values of this. So it hard update statue of current values and add new status in database,
$chks = array('multicolor','resizable','showRuler','namesNumbersEnabled');
foreach ($chks as $chk) {
$product->setAttribute($chk, (Input::has($chk)) ? true : false);
}
This is my json object save in data column
{"user_token":"ad48c412-3866-4ac9-adf6-3328911ae46c",
"order_info":
{"order_id":"CGC12345678","company_id":32,"price":1000.5,"currency":"MYR",
"products":[
{"type":"HR_ECLAIM","name":"HREClaim","is_fixed_price":true,"price":500.5,"currency":"MYR"},
{"type":"HR_ELEAVE","name":"HRELeave","is_fixed_price":true,"price":500,"currency":"MYR"}
],
"total_invoices":200,"total_staffs":80},"url":"https://drive.google.com/open?id=1Is6QsnuMLu9ZIpqeEzR2O2Ve1wUyF92aVCg55kWsOgc"}
i load [order_info][products][type] as checked products in while i load all the products from env file. I only need to save checked check box products in db.
Can someone helps me?

This is the complete working solution i done for my question!
public function edit($id, $attributes){
$orders = (new Agos())->load($id);
$json = $orders->data;
$json = json_decode($json);
$checkedit= $attributes['check_list'];
if (is_array($checkedit) || is_object($checkedit))
{
foreach($checkedit as $chked1){
$exists = false;
foreach($json->products as $key => $val)
{
// update if products exists
if($val->type == $chked1) {
$val->status = 'true';
$exists = true;
}
if(array_key_exists('status', $val)) {}
else{ $val->status = 'false';}
}
if($chked1 == 'FIN_REPORTING')
{
$name = 'Finance reporting & book keeping';
}
elseif ($chked1 == 'FIN_ADVISORY')
{
$name = 'Finance Advisory';
}
elseif ($chked1 == 'PAYROLL_HRDB')
{
$name = 'PAYROLL_HRDB';
}
elseif ($chked1 == 'HR_ELEAVE')
{
$name = 'HR E-Leave';
}
else
{
$name = 'HR E-Claim';
}
//if products not exists add new products
if(!$exists) {
$newproduct = new \stdClass();
$newproduct->type = $chked1;
$newproduct->name = $name;
$newproduct->is_fixed_price = false;
$newproduct->currency = "MYR";
$newproduct->status = "true";
array_push($json->products, $newproduct);
}
}
}
//remove all products that have status = false
foreach($json->products as $index => $product) {
if ( $product->status == "false") {
unset($json->products[$index]);
}
}
$json->products = array_values($json->products);
json_encode($json, JSON_PRETTY_PRINT);
//remove status element from products
foreach($json->products as $index => $product) {
unset($product->status);
}
$json->products = array_values($json->products);
json_encode($json, JSON_PRETTY_PRINT);
$json->google_drive_url= $attributes['data'];
$json->remark= $attributes['remark'];
$json->status= $attributes['status'];
$json->total_invoices= $attributes['total_invoices'];
$json->total_staffs= $attributes['total_staffs'];
$json1 = json_encode($json);
$status = $attributes['status'];
$total_price = str_replace(',','', $attributes['total_price']);
DB::table('orders')
->where('id', $id)
->update(['data' => $json1,'status' => $status, 'price' => $total_price]);
}

Related

Laravel array index variable won't pass to redirected view

My $data['orders'] won't pass to my redirected view and i get the error "Undefined index: orders (View: /.../pages/userhome.blade.php)". For some reason the $data['user'] variable will pass and show its value but the 'orders' one will not. Ive changed the name and why way i create the data array but its still won't work.
pagescontroller.php
$this->validate($request, []);
$data = array();
$orderdate = date('Y-m-d H:i:s');
$data['user'] = Auth::user();
$ordernum = Str::uuid()->toString();
$sum = 0;
$cart = DB::table('cart')->where('buyerid', '=', auth()->user()->id)->paginate(10);
foreach ($cart as $item) {
$product = Product::find($item->itemid);
$orderitem = new Orderitem;
$orderitem->buyerid = $item->buyerid;
$orderitem->productid = $product->id;
$orderitem->quantity = $item->quantity;
$orderitem->ordernumber = $ordernum;
$orderitem->dateordered = $orderdate;
$sum = $sum + (number_format($product->price * $item->quantity, 2));
$product->sold = $product->sold + $item->quantity;
$orderitem->save();
}
$order = new Order;
$order->buyerid = Auth::user()->id;
$order->customeremail = Auth::user()->email;
$order->customeraddress = ''; //$request->input('address');
$order->total = number_format($product->price * $item->quantity, 2);
$order->dateordered = $orderdate;
$order->city = ''; //$request->input('city');
$order->zipcode = ''; //$request->input('zipcode');
$order->ordernumber = $ordernum;
$order->total = $sum;
$order->save();
$orders = DB::table('orders')->where('buyerid', '=', auth()->user()->id)->get();
$data['orders'] = $orders;
return redirect("/userhome/{$data['user']->name}")->with('success', 'Your order has been sent. A confirmation will be sent to your email shortly.')->with(compact($data));
userhome.blade.php
the code fails right at the '#if(count($data['orders']) > 0)' line
<h1>{{ $data['user']->name }}</h1>
<section class="topsellers">
<h2>Orders</h2>
<div class="container flex">
#if (count($data['orders']) > 0)
#foreach ($data['orders'] as $order)
<div class="productcard" }>
<p>test</p>
</div>
#endforeach
#else
<p>Looks like you have no current orders.</p>
#endif
</div>
{{-- {{$data['products']->links()}} --}}
</section>
Use your controller method to get the orders
First: change your redirect like below:
return redirect("/userhome/{$data['user']->name}")
->with('success', 'Your order has been sent. A confirmation will be sent to your email shortly.');
Second : Query from your orders table in controller method then pass to the view like below code;
public function someMethod()
{
$data['orders'] = DB::table('orders')->where('buyerid', '=', auth()->user()->id)->get();
return view('userhome', $data);
}

Laravel Product Filter by Price

I have a filter route to filter my products by brand & weight & count and taste and all are working fine but when i want to add a sort filter its not working, i want to sort it by pirce ( Ascending and descending).
here is my codes
Route:
Route::match(['get', 'post'], 'products/filter', [SearchController::class, 'filterall']);
SearchController:
public function filterall(Request $request){
$data = $request->all();
// echo "<pre>"; print_r($data);
$brandUrl = "";
$weightUrl = "";
$countUrl = "";
$tasteUrl = "";
$sortUrl = "";
if(!empty($data['brandFilter'])){
foreach ($data['brandFilter'] as $brand){
if(empty($brandUrl)){
$brandUrl = "&brand=".$brand;
}else{
$brandUrl .= "-".$brand;
}
}
}
if(!empty($data['weightFilter'])){
foreach ($data['weightFilter'] as $weight){
if(empty($weightUrl)){
$weightUrl = "&weight=".$weight;
}else{
$weightUrl .= "-".$weight;
}
}
}
if(!empty($data['countFilter'])){
foreach ($data['countFilter'] as $count){
if(empty($countUrl)){
$countUrl = "&count=".$count;
}else{
$countUrl .= "-".$count;
}
}
}
if(!empty($data['tasteFilter'])){
foreach ($data['tasteFilter'] as $taste){
if(empty($tasteUrl)){
$tasteUrl = "&taste=".$taste;
}else{
$tasteUrl .= "-".$taste;
}
}
}
if(!empty($data['sort'])){
foreach ($data['sort'] as $sort){
if(empty($sortUrl)){
$sortUrl = "&sort=".$sort;
}else{
$sortUrl .= "-".$sort;
}
}
}
$finalUrl = "category/".$data['url_id'].'/'.$data['url_slug']."?".$brandUrl.$weightUrl.$countUrl.$tasteUrl.$sortUrl;
return redirect::to($finalUrl);
}
*** My View Controller ***
public function allCategory(Request $request, $id){
$catt = DB::table('categories')->where('id', $id)->first();
$products = Product::where('category_id', $catt->id)->where('status', '1')
->orderBy('brand_id', 'ASC');
if(!empty($_GET['brand'])){
$brandArray = explode('-', $_GET['brand']);
$products = $products->whereIn('brand_id', $brandArray);
}
if(!empty($_GET['weight'])){
$weightArray = explode('-', $_GET['weight']);
$products = $products->whereIn('product_weight', $weightArray);
}
if(!empty($_GET['count'])){
$countArray = explode('-', $_GET['count']);
$products = $products->whereIn('product_count', $countArray);
}
if(!empty($_GET['taste'])){
$tasteArray = explode(',', $_GET['taste']);
foreach ($tasteArray as $taste){
$products = $products->where('product_taste','LIKE', "%$taste%");
}
if(!empty($_GET['sort'])){
$sortArray = explode('-', $_GET['sort']);
$products = $products->orderBy('selling_price', $sortArray);
}
}
$products = $products->paginate(12);
return view('pages.all_category', compact('products', 'catt'));
}
and this is the view code:
<div class="row" id="search-results">
<div class="col-lg-12 col-md-12">
<div class="toolbar toolbar-products">
<div class="toolbar-sorter sorter">
<label class="sorter-label" for="sort">Sort By</label>
#if(!empty($_GET['sort']))
<?php $sortArray = explode('-', $_GET['sort']) ?>
#endif
<select id="sort" name="sort[]" class="sorter-options" onchange="javascript:this.form.submit();">
<option value="">Select</option>
#if(!empty($_GET['sort']))
<?php $price = $_GET['sort'] ?>
#endif
<option value="ASC" #if(!empty($sortArray) && in_array('ASC', $sortArray)) selected="" #endif>Lowest Price</option>
<option value="DESC" #if(!empty($sortArray) && in_array('DESC', $sortArray)) selected="" #endif>Highest Price</option>
</select>
</div>
</div>
</div>
</div>
im doing this by Form in page.
I think orderBy in front Controller is not working is there other way to sort that?

Add and update products to session cart in Laravel

I am building a shopping cart for guests with sessions in laravel.
I can add one product with quantity to the session variable 'cart.' However, when I add the same product again, I cannot increment quantity as I cannot search for the same product ID in the array.
Controller
public function addToSessionCart(Request $request, $id)
{
if (session()->has('cart')) {
$oldCart = session()->get('cart');
$cartdata = $oldCart;
if (array_key_exists('product_id', $cartdata)) {
if (in_array($id, $cartdata['product_id'], true)) {
$cartdata['quantity'] += 1;
} else {
$cartdata['product_id'] = $id;
$cartdata['quantity'] = 1;
}
}
} else {
$cartdata = [];
$cartdata['product_id'] = $id;
$cartdata['quantity'] = 1;
}
session()->put('cart', $cartdata);
session()->flash('message', 'Item added to cart !');
return back();
}
I am passing data to the cart from my AppServiceProvider:
view()->composer('*', function ($view) {
if (Auth::check()) {
$cart_items = Cart::where('user_id', Auth::user()->id)->with('product')->get();
$cart_items_count = Cart::where('user_id', Auth::user()->id)->count();
$menus = Menu::where('status', '1')->orderBy('order', 'ASC')->get();
$view->with(['cart_items' => $cart_items, 'cart_items_count' => $cart_items_count, 'menus' => $menus]);
} else {
$cart_items = null;
$session_cart_items = null;
if (\Session::get('cart')) {
$session_cart_items = [];
foreach (session('cart') as $session_cart_items[]) {
$session_cart_items['product'] = Product::where('id', session('cart.product_id'))->get();
$session_cart_items['quantity'] = session('cart.quantity');
}
}
$cart_items_count = count(\Session::get('cart'));
$menus = Menu::where('status', '1')->orderBy('order', 'ASC')->get();
$view->with([
'cart_items' => $cart_items, 'cart_items_count' => $cart_items_count, 'menus' => $menus,
'session_cart_items' => $session_cart_items,
]);
}
});
View
#foreach($session_cart_items['product'] as $key => $name)
<div class="product-cart">
<div class="product-image">
<img src="/frontend/assets/images/{{ $name->image }}" alt="image">
</div>
<div class="product-content">
<h3>{{$name->name}}</h3>
<div class="product-price">
<span>{{ $session_cart_items['quantity'] }}</span>
<span>x</span>
₹ <span class="price">{{ $name->price }}</span>
</div>
</div>
</div>
#php
$total += ($name->price * $session_cart_items['quantity']);
#endphp
#endforeach
I want the quantity to be incremented when the same product gets added to the cart. If not, add a new product id and quantity to the session array.
This line needs to be changed:
foreach (session('cart') as $session_cart_items[]) {
You cannot use [] for reading.
foreach (session('cart') as $session_cart_items) {

Retrieve data from laravel to blade

I'm a beginner in laravel and at uni our task was to retrieve data from a a file called pms.php which contains all the results for the prime minsters such as name, year and state. No matter what I do I cant get it to work.
This is my web.php file:
require(app_path().'/pms.php');
// To do: Display search form
Route::get('/', function()
{
return view('search_form');
});
// To do: Perform search and display results
Route::get('search', function()
{
//$name = request('name');
//$year = request('from', 'to');
//$state = request('state');
$pms = search('name','from','to','state');
return view('search')->with('name', $pms)
->with('from', $pms)->with('to', $pms)->with('state', $pms);
});
/* Functions for PM database example. */
/* Search sample data for $name or $year or $state from form. */
function search($name, $year, $state) {
$pms = getPms();
// Filter $pms by $name
if (!empty($name)) {
$results = array();
foreach ($pms as $pm) {
if (stripos($pm['name'], $name) !== FALSE) {
$results[] = $pm;
}
}
$pms = $results;
}
// Filter $pms by $year
if (!empty($year)) {
$results = array();
foreach ($pms as $pm) {
if (strpos($pm['from'], $year) !== FALSE ||
strpos($pm['to'], $year) !== FALSE) {
$results[] = $pm;
}
}
$pms = $results;
}
// Filter $pms by $state
if (!empty($state)) {
$results = array();
foreach ($pms as $pm) {
if (stripos($pm['state'], $state) !== FALSE) {
$results[] = $pm;
}
}
$pms = $results;
}
return $pms;
}
This is my search.blade.php file
#extends('layouts.master')
#section('title')
Query Search Result
#endsection
#section('content')
Search result for {{ $name }} {{ $year }} {{ $state }}
#endsection
This is my search_form.blade.php:
#extends('layouts.master')
#section('title')
Search Form
#endsection
#section('content')
<p>
<h2>Australian Prime Ministers</h2>
<h3>Query</h3>
<form method="get" action="search">
{{csrf_field()}}
<table>
<tr><td>Name: </td><td><input type="text" name="name"></td></tr>
<tr><td>Year: </td><td><input type="text" name="year"></td></tr>
<tr><td>State: </td><td><input type="text" name="state"></td></tr>
<tr><td colspan=2><input type="submit" value="Search">
<input type="reset" value="Reset"></td></tr>
<table>
</form>
</p>
#endsection
Do you guys know why it isn't working? The issue I'm facing right now is:
htmlspecialchars() expects parameter 1 to be string, array given (View: /home/ubuntu/workspace/Week4/assoc-laravel/resources/views/search.blade.php)
Send data in compact(),
return View::make('foo.bar')
->with(compact('test'));
OR
Recommended ->
return view('foo.bar', compact('your_php_variable'))

Echo custom options with the values for Magento

How to echo all custom options with all the values by product id for Magento?
If i am using this code...
public function ws_productdetail($store_id, $service, $productid)
{
$res=array();
$productsCollection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToFilter('entity_id', array('in' => $productid))
->addAttributeToSelect('*');
$all_product_images = array();
$product = Mage::getModel('catalog/product')->load($productid);
foreach ($product->getMediaGalleryImages() as $image) {
$all_product_images[] = $image->getUrl();
}
foreach($productsCollection as $product)
{
$res["id"] = $product->getId();
$res["name"] = $product->getName();
$res["price"] = number_format($product->getPrice(),2);
}
return($res);
}
... how can I get the custom options?
For example say for a product JEANS, COLOR with various values {blue,black,brown} and every option will have different prices, then how i get all this information as output.
According to my understanding, you want to show the all DROPDOWN custom option on view page then try this.
$productid = $_product->getId(); //PLEASE ENTER THE PRODUCT ID HERE
$product = Mage::getModel("catalog/product")->load($productid);
$attVal = $product->getOptions();
$optStr = "";
foreach($attVal as $optionKey => $optionVal)
{
$optStr.='<dl><div class="custom_select_css">
<dt><label>'.$optionVal->getTitle().'</label></dt>
<dd class="last">
<div class="input-box">';
$optStr.= "<select id='".$optionVal->getId()."' name='options[".$optionVal->getId()."]'>";
foreach($optionVal->getValues() as $valuesKey => $valuesVal)
{
$price = number_format($valuesVal->getPrice(),0);
$optStr.= "<option price='".number_format($valuesVal->getPrice(),0)."' data-label='".$colorarray[$valuesVal->getTitle()]."' value='".$valuesVal->getId()."'>".$valuesVal->getTitle(); if($price != '0'){$optStr.=" +$".number_format($valuesVal->getPrice(),2);}$optStr.=" </option>";
}
$optStr.= "</select></div></dd><div></dl>";
}
echo $optStr;
------------------------------ UPDATED CODE -------------------------------
public function ws_customdetail ($productid)
{
$all_custom_option_array = array();
$product = Mage::getModel("catalog/product")->load($productid);
$attVal = $product->getOptions();
$optStr = "";
$inc=0;
foreach($attVal as $optionKey => $optionVal)
{
$all_custom_option_array[$inc]['custom_option_name']=$optionVal->getTitle();
$all_custom_option_array[$inc]['custom_option_id']=$optionVal->getId();
$inner_inc =0;
foreach($optionVal->getValues() as $valuesKey => $valuesVal)
{
$all_custom_option_array[$inc]['custom_option_value_array'][$inner_inc]['title'] = $valuesVal->getTitle();
$all_custom_option_array[$inc]['custom_option_value_array'][$inner_inc]['price'] = number_format($valuesVal->getPrice(),0);
$inner_inc++;
}
$inc++;
}
return $all_custom_option_array;
}
Use ws_customdetail function and pass the product id in it.
THIS IS THE EXACT CODE THAT WORKED FOR ME.
public function customdetail($productid){
$all_custom_option_array = array();
$product = Mage::getModel("catalog/product")->load($productid);
$attVal = $product->getOptions();
$optStr = "";
$inc=0;
foreach($attVal as $optionKey => $optionVal){
$all_custom_option_array[$inc]['custom_option_name']=$optionVal->getTitle();
$all_custom_option_array[$inc]['custom_option_id']=$optionVal->getId();
$all_custom_option_array[$inc]['custom_option_type']=$optionVal->getType();
$all_custom_option_array[$inc]['custom_option_value_array'];
$inner_inc =0;
foreach($optionVal->getValues() as $valuesKey => $valuesVal){
$all_custom_option_array[$inc]['custom_option_value_array'][$inner_inc]['title'] = $valuesVal->getTitle();
$all_custom_option_array[$inc]['custom_option_value_array'][$inner_inc]['price'] = number_format($valuesVal->getPrice(),0);
$inner_inc++;}
$inc++;}
return $all_custom_option_array;}
HOPE THIS WILL HELP SOMEONE :)
THANX

Categories