i want to create a shop site by laravel.
i want to create cart page and cart page showing all product that user want to shop it.
i create a session for every product that user want to shop.
i have some session in laravel like this
$_SESSION[cart_133] = [
'product' => 'test1',
'quantity' => '3',
'price' => '30'
];
$_SESSION[cart_30] = [
'product' => 'test2',
'quantity' => '1',
'price' => '50'
];
$_SESSION[cart_65] = [
'product' => 'test3',
'quantity' => '10',
'price' => '653',
];
and i wan to showing them like this
<p>test1</p>
<p>3</p>
<p>30</p>
<hr>
<p>test2</p>
<p>1</p>
<p>50</p>
<hr>
<p>test3</p>
<p>10</p>
<p>653</p>
<hr>
<hr>
<p>all price 733</p>
If you want to do it Laravel way, you have to define relations.
Category Model (each category might have some products)
public function products()
{
return $this->hasMany('App\Product');
}
Product model (each product belongs to some category)
public function category()
{
return $this->belongsTo('App\Category');
}
Then when you want to get categories with their products, you can use Eager Loading.
Controller:
$categories = Category::with('products')->get();
View:
#foreach ($categories as $cat)
#foreach ($cat->products as $product)
<!-- product data -->
#endforeach
#endforeach
you can use call all session an use substr function to limit one suffix.
you can use this
$x = [];
foreach(Session::all() as $name => $val){
if(substr($name , 0 , 5 ) == "cart_"){
$x[$name] = $val;
}
}
echo '<pre>';
print_r($x;);
Related
In my project, all users are stored in the user table. The ones who are suppliers, their user key goes into the supplier table.
Each product can have multiple variations. The key product goes into the productattribute table.
Each supplier can have multiple products with multiple attributes.
So there is a many to many table of product attributes & suppliers named productsupplier.
I want to give the option to the user to make a new Purchase Order.
The Purchase Order will be for the supplier.
The user will select the supplier and then all the products that are assigned to him will show up.
The problem is that a product with the same name can have different attributes. Therefore, when I write the code for the products belonging to a supplier to show up, one product (which has different variations) shows up multiple times.
I have been struggling to use distinct or unique functions to show the name of one product once only, but since it's in a foreach loop, it doesn't work.
Here's the code:
public function new_po_next(Request $request)
{
$product = array();
$supplier = \App\supplier::where('user_id', $request->supplier)->first();
$productsupplier = \App\productsupplier::where('supplier_id', $supplier->id)->get();
foreach ($productsupplier as $ps) {
$productattribute = \App\productattribute::where('id', $ps->productattribute_id)->first();
$prod = \App\product::where('id', $productattribute->product_id)->first();
$product [] = [
'prod_supp_id' => $ps->id,
'prod_supp_prodattid' => $ps->productattribute_id,
'prod_supp_cost' => $ps->cost,
'prod_att_id' => $productattribute->id,
'prod_att_color' => $productattribute->color_id,
'prod_att_size' => $productattribute->size_id,
'prod_att_material' => $productattribute->material_id,
'prod_att_prodid' => $productattribute->product_id,
'prod_id'=>$prod->id,
'prod_name' =>$prod->name,
];
}
$status = $request->status;
$deldate = $request->deldate;
$discount = $request->discount;
return view("vendor.new-po-next")
->with('status', $status)
->with('deldate', $deldate)
->with('discount', $discount)
->with('product', $product);
}
This code is giving the following result (it's the correct result as product1 has 1 variation only but product5 has 3 variations).
What I want is that it shows 'product1' and 'product5' (product5 ONCE only).
If the user selects product5, then it shows the rest of the variations to select from.
Please let me know how it can be done!
How about using Laravel collections, you can convert your array to collection,
// After the loop is finished.
$productCollection = collect($product);
$groupedProductCollection = $collection->groupBy('prod_name');
$groupedProduct = $groupedProductCollection->all(); // all method will convert it back to array
// then return the value
return view("vendor.new-po-next")
->with('status', $status)
->with('deldate', $deldate)
->with('discount', $discount)
->with('product', $groupedProduct);
Working
Lets say your product array is like this
$product = [
['prod_name' => 'product5', 'prod_supp_cost' => '$4'],
['prod_name' => 'product5', 'prod_supp_cost' => '$3'],
['prod_name' => 'product1', 'prod_supp_cost' => '$6'],
]
Then after groupby it will be like,
[
'product5' => [
['prod_name' => 'product5', 'prod_supp_cost' => '$4'],
['prod_name' => 'product5', 'prod_supp_cost' => '$3'],
],
'product1' => [
['prod_name' => 'product1', 'prod_supp_cost' => '$6'],
],
]
Then you you show the array_keys in list and its values separately when the user clicks on it.
EDIT: How to use it in frontend
<select id="" name="">
#foreach(array_keys($groupedProduct) as $product_names)
<option value="{{ $product_names }}"></option>
#endforeach
</select>
If someone clicks then show it using $groupedProduct[$product_names]
Though the long term and best solution as suggested by #miken32 would be to use eloquent relationships & let relations handle all the querying so that there is no need for a for loop.
I have a product table which has price, name, stock etc. and color_products table which has color_id, product_id. I want to store a product to the database with selected colors so far I'm getting an error Invalid argument supplied for foreach(). How can I fix this?
Controller
$formInput=$request->all(); //If I do dd($formInput) I see all data
$product = product::create(array_merge($formInput, [
'user_id' => Auth::user()->id
]));
// Insert color to the database
$store_color = [];
$colors = $request->color_id;
foreach ($colors as $color) {
$ouzColor = $color->save;
$store_color[] = [
'product_id' => $product->id,
'color_id' => $ouzColor
];
}
ColorProduct::insert($store_color);
Blade file
<select multiple name="color_id" id="color">
<option value=""> --Select Colors -- </option>
#foreach($colors as $color)
<option value="{{ $color->id }}" >{{$color->name}}</option>
#endforeach
</select>
try to rename your select field to be something like that <select multiple name="color_id[]" id="color">
let's take it a step by a step.
$product = Product::create([
'field 1' => $request->field1,
'filed 2' => $request->field2,
'user_id' => \Auth::user()->id,
]);
$store_color = [];
foreach ($request->color_id as $index=>$color) {
$store_color[$index] = [
'product_id' => $product->id,
'color_id' => $color,
];
}
ColorProduct::insert($store_color);
of course, you need to change filed1 and 2 with its real names and value
Please, I have a function in my controller.
I want to query the stock table to select the list of product_id and after select, it should go to product table to display the NAME of product to the user instead of product_id.
public function getStockList()
{
$stock = DB::table("stocks")->pluck("product_id","product_id")->all();
$products = DB::table("products")->pluck("name")->where('id', $stock);
return view('shop.shop')->with(['stocks' => $stocks,
'stock' => $stock, 'products' => $products]);
}
My PHP blade has
{!! Form::select
(
'stock',
['' => 'Select'] +$stock,'',
array(
'class'=>'form-control',
'id'=>'country',
'style'=>'width:350px;'
)
)!!}
{!! Form::select
(
'product_id',
[''=>'Select Supplier'] + $products, null,
['class'=>'form-control']
)!!}
Basically, I don't want product_id to be displayed to the user but the product name.
Try this
public function getStockList()
{
$stock = DB::table("stocks")->pluck("product_id");
$products = DB::table("products")->whereIn('id', $stock)->pluck("name","id");
return view('shop.shop')->with([
'stocks' => $stocks,
'stock' => $stock,
'products' => $products
]);
}
Replace your product list select box with the following
{!! Form::select('product_id',$products,null, ['class'=>'form-control','placeholder'=>'Select Products'])!!}
you need array to pass in form
/* $product_array = ['1' => 'product 1', '2' => 'product 2', '3' => 'product 3']; */
so in your controller
$product_array = []
foreach($products as $product){
$product_array[$product->id] = $product->name;
}
return view('shop.shop')->with(['stocks' => $stocks,
'stock' => $stock, 'products' => $products , 'product_array'=>$product_array]);
And in your view
{{!! Form::select('product_id', $product_array , null, ['class'=>'form-control'])!! }}
hope this will help.
I am doing a shopping cart using code-igniter. While I can do the add cart functions, I'm somewhat confused with how to update them with regards to database. All I want is when I change the item quantity in the cart and click update ,both the cart and database must be updated for that particular item.I tried to do it but couldn't get it.Can someone please enlighten me what to do?
controller code
$this->load->model('user_m');
$result['query'] = $this->user_m->get($id); // inserts coresponing item
foreach ($result['query'] as $row)
$id = $row->pid;
$qty = $a;
$quan=$row->quantity;
$price = $row->pprice;
$name = $row->pname;
$q=$quan-$a; // for remainig stock i.e total qty-user qty
$data = array(
'id' => $id,
'qty' => $qty,
'price' => $price,
'name' => $name,
'stock' =>$q
);
$this->cart->insert($data);
$this->load->model('user_m');
$result['qry'] = $this->user_m->up_cart($id,$q);
redirect($_SERVER['HTTP_REFERER']);
}
just tell me how to update pls!
when ever you add any product in cart, it will generate an uniq row ID and that will be unique for each and every product and hence you need to update quantity by that row ID
$data = array(
'rowid' => 'b99ccdf16028f015540f341130b6d8ec',
'qty' => 3
);
$this->cart->update($data);
// Or a multi-dimensional array
$data = array(
array(
'rowid' => 'b99ccdf16028f015540f341130b6d8ec',
'qty' => 3
),
array(
'rowid' => 'xw82g9q3r495893iajdh473990rikw23',
'qty' => 4
),
array(
'rowid' => 'fh4kdkkkaoe30njgoe92rkdkkobec333',
'qty' => 2
)
);
$this->cart->update($data);
Now you want to know about how you will get row id.
$cart=$this->cart->contents();
it will return whole array of cart and when you listing it on webpage, please associate row id with quantity text box to update that particular product.
please check following url:
https://ellislab.com/codeigniter/user-guide/libraries/cart.html
I have a problem with a recursive function that takes too many resources to display a child-parent relation in a dropdown list. For example:
home
-menu 1
-menu 2
home 1
-menu 3
-menu 4
I've written some code for a recursive call to the database each time, so that's the reason why my code takes so many resources to run.
Below is my code:
--call recursive
$tmp = $this->get_nav_by_parent(0);
$a_sel = array('' => '-Select-');
$a_sel_cat = array('home' => 'home');
$this->get_child_nav_cat($tmp, 0, $a_sel);
--
public function get_nav_by_parent($parent) {
$all_nav = $this->db
->select('id, title, parent')
->where('parent',$parent)
->order_by('position')
->get('navigation_links')
->result_array();
$a_tmp = array();
foreach($all_nav as $item)
{
if($parent != 0){
$item['title'] = '--' . $item['title'];
}
$a_tmp[] = $item;
}
return $a_tmp;
}
-- Recursive function
public function get_child_nav_cat($a_data, $parent, &$a_sel) {
foreach($a_data as $item) {
$a_sel[$item['page_slug_key']] = $item['title'];
$atmp = $this->get_nav_by_parent($item['id']);
$this->get_child_nav_cat($atmp, $item['id'], $a_sel);
}
return $a_sel;
}
Please give me suggestions for the best solution to display the data as child-parent relationship in select box.
Thanks in advance!
Best way to display parent child relationship is mentain parent and child flag in Database instead of
fetching value using loop.
In your case Home, Home 1 is parent flag and menus belong on child flag.
fetch data from db and your loop look like this:-
$arr = array(0 => array('name' => 'home','parent' => 0),
1 => array('name' => 'menu 1 ','parent' => 1),
2 => array('name' => 'menu 2 ','parent' => 1),
3 => array('name' => 'home 1','parent' => 0),
4 => array('name' => 'menu 3 ','parent' => 2),
5 => array('name' => 'menu 4','parent' => 2)
);
$dd_html = '<select>';
foreach($arr as $k => $v){
if($v['parent'] == 0 )
$dd_html .='<option>'.$v['name'].'</option>';
else
$dd_html .='<option>--'.$v['name'].'</option>';
}
$dd_html .= '</select>';
echo $dd_html;
Output :-
home
-menu 1
-menu 2
home 1
-menu 3
-menu 4
Set ParentID=0 for detecting root item
then execute this:
SELECT * FROM table ORDER BY ParentID, ID
Then iterate through result and when ParentID changed, create new level.