codeignietor cart only one product is adding to cart - codeigniter

while doing a cart page i am able to add only one product to cart class,antor product is not entering the class.My controller,model
controller class
public function buy($id){
$product = $this->mproduct->find($id);
$res['result'] = $product;
$data = array(
'id' => $product->pro_id,
'qty' => '1',
'price' => $product->pro_price,
'name' => $product->pro_title,
);
$array = (array) $data;
$this->cart->insert($array);
$this->load->view('cart',$res);
}
public function delete($row_id){
$this->cart->update(array('rowid' => $row_id,'qty' => 0));
$this->load->view('cart');
}
public function update(){
$i=1;
foreach ($this->cart->contents() as $items) {
$this->cart->update(array('rowid' =>$items['rowid'],'qty' => $_POST['qty'.$i]));
$i++;
}
$this->load->view('cart');
}
The Model
public function find($id)
{
$this->db->where('pro_id',$id);
return $this->db->get('products')->row();
}

Related

How to use livewire pagination with public properties?

I'm facing a weird problem that only accurs when I use pagination with livewire components,
this is the error:
BadMethodCallException
Method Illuminate\Support\Collection::items does not exist.
I know what this errors means, the problem is why it only accurs when I change page in pagination:
this is my Component:
<?php
namespace App\Http\Livewire\Admin;
use Livewire\Component;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
use App\Models\Product;
use App\Models\Category;
use File;
use GlobalsHelper;
class Products extends Component
{
use WithPagination, WithFileUploads;
public $products;
public $subcategories;
// Form
public $name;
public $description;
public $price;
public $quantity;
public $category_id = null;
public $sub_category_id = null;
public $image;
public $selected = [];
public $query = '';
public $filter_by_category = '';
protected $paginationTheme = 'bootstrap';
public function render()
{
$pagination = $this->products;
$this->products = collect($this->products->items());
return view('livewire.admin.products', [
'categories' => Category::all(),
'subcategories' => $this->subcategories,
'products' => $this->products,
'pagination' => $pagination
]);
}
// public function render()
// {
// return view('livewire.admin.products', [
// 'categories' => Category::all(),
// 'subcategories' => $this->subcategories,
// 'products' => $this->products,
// ]);
// }
public function mount()
{
$this->getSubcategories();
$this->index();
}
public function getSubcategories()
{
$this->subcategories = [];
if ( !$this->category_id )
{
$this->category_id = (Category::first()) ? Category::first()->id : null;
}
$category = Category::find($this->category_id);
if ( !$category )
{
return null;
}
$this->subcategories = $category->children;
$this->sub_category_id = ($this->subcategories->first()) ? $this->subcategories->first()->id : null;
}
public function store()
{
$fields = $this->validate([
'name' => ['required', 'string', 'min:5', 'max:250'],
'description' => ['string', 'max:250'],
'price' => ['required', 'numeric', 'min:1'],
'quantity' => ['required', 'numeric', 'min:1'],
'category_id' => ['nullable'],
'sub_category_id' => ['nullable'],
]);
$fields['user_id'] = GlobalsHelper::auth()->id;
$product = Product::create($fields);
if ( !$product )
{
session()->flash('error', __('messages.error_create'));
return;
}
// upload image
$this->storeImage($product);
$this->resetFields();
session()->flash('success', __('messages.success_create'));
}
public function search()
{
$results = Product::where('name', 'LIKE', '%'.$this->query.'%')
->orderBy('id', 'desc')->paginate(5);
$this->products = $results;
}
public function index()
{
$this->products = Product::orderBy('id', 'desc')->paginate(5);
}
public function filterByCategory()
{
$results = Product::where('category_id', '=', $this->filter_by_category)
->orderBy('id', 'desc')->paginate(5);
$this->products = $results;
}
// private
private function resetFields()
{
$this->name = null;
$this->description = null;
$this->price = 0;
$this->quantity = 1;
$this->image = null;
$this->filename = '...';
}
private function storeImage($product)
{
$this->validate([
'image' => ['nullable', 'image', 'max:1024'],
]);
if ( $this->image )
{
// Delete old image if exists
if ( $product->image )
{
File::delete([$product->image->fullpath]);
}
$filename = sha1( uniqid('', true) );
$ext = $this->image->getClientOriginalExtension();
$fullpath = $this->image->store(GlobalsHelper::PRODUCTS_UPLOADS_DIR.'/'.$product->id, 'public');
$product->update([
'image' => [
'name' => basename($fullpath),
'type' => $ext,
'fullpath' => GlobalsHelper::STORAGE_DIR.$fullpath,
'url' => asset(GlobalsHelper::STORAGE_DIR.$fullpath)
]
]);
}
}
}
The idea is that I want to achieve search, store, update, delete, filter operations in same compoenent like in laravel controller, I found solutions online, but only 50% of what I need to achieve.
I have been wasting a lot of time trying to figure this out.
If any one would help me, I will be much appreciated.
At first glance without seeing the view, you are getting the $produts via the mount() method, this will only run ONCE when the livewire component is first rendered. From the docs:
mount() is only ever called when the component is first mounted and will not be called again even when the component is refreshed or rerendered.

How to make a CRUD for a PackageItem table and get the Item via foreignKey in another table? in Laravel

This is my Item model. I have made a function arrayPackageItemSelect that gets the id and equivalent it to the item name.
class Item extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'name',
'price',
'itemdescription',
'activeInactive'
];
public function packageitems()
{
return $this->hasMany(PackageItem::class);
}
public static function arrayPackageItemSelect()
{
$arr = [];
$items = Item::all();
foreach($items as $item){
$arr[$item->id] = $item->name;
}
return $arr;
}
}
my PackageItem Model
class PackageItem extends Model
{
protected $fillable = [
'user_id',
'item_id',
'price'
];
protected $table='packageitems';
public static function itemModel()
{
return $this->belongsTo(Item::class);
}
}
my PackageItem Controller (CREATE) and getting the Item ID from another table (Foreign key) so I can put a category for it.
public function addPackageItem(Request $request)
{
$user = Auth::user();
$item = Item::arrayPackageItemSelect();
echo $item; // when I echo this I get Array to Conversion String in POSTMAN
$fields = $request->validate([
'user_id' => 'required',
'item_id' => 'required',
'price' => 'required|numeric'
]);
// // echo $items;
$package = PackageItem::create([
'user_id' => $user->id,
'item_id' => $item,
'price'=> $fields['price']
]);
return response($package, 201);
}
What I get when I echo the Items
The results I get from POSTMAN
My Schema
This is where my reference is https://www.artofcse.com/learning/product-view-insert-update-delete
Can anybody help me what is wrong?
In your controller (addPackageItem method):
$package = PackageItem::create([
'user_id' => $user->id,
'item_id' => $fields['item_id'],
'price'=> $fields['price']
]);
Also, i think there is an error in your PackageItem model. belongsTo should not be called in a static method :
public function itemModel()
{
return $this->belongsTo(Item::class);
}

Laravel update pivot table

In laravel I'm trying to update a row from a pivot table. I have this relationships:
Invoice.php
class Invoice extends Model
{
public function items() {
return $this->belongsToMany('App\Item', 'invoice_items', 'invoice_id', 'item_id')->withPivot('quantity');
}
Item.php
class Item extends Model
{
public function invoices() {
return $this->belongsToMany('App\Invoice' ,'invoice_items', 'item_id', 'invoice_id')->orderBy('created_at', 'desc')->withPivot('quantity');
}
}
InvoiceItem.php
class InvoiceItem extends Pivot
{
protected $fillable = [
'quantity',
];
public function __construct(Model $parent, array $attributes,
$table, $exists = false)
{
parent::__construct($parent, $attributes, $table, $exists);
}
}
and in InvoicesController.php I have method update:
public function update(Request $request, $id)
{
$invoice = Invoice::findOrFail($id);
$invoice->update([
'number' => $request->number,
'status' => $request->status,
'place_issue' => $request->place_issue,
'date_issue' => $request->date_issue,
'date_payment' => $request->date_payment,
'description' => $request->description,
'company_id' => $request->company_id,
'user_id' => $request->user_id,
]);
Invoice::find($id)->items()->updateExistingPivot($request->quantity, ['quantity' => $request->quantity]);
return redirect('listInvoice');
}
Every time I try to update the field "quantity" is the old value. What am I doing wrong?
As each invoice may have multiple items, you can loop through and update the quantity of the item by its key.
I'm not sure what $request->quantity is returning. You may need some additional logic to ensure you are updating the correct item.
$items = $invoice->items->pluck('name', 'id')->toArray();
foreach ($items as $key => $item) {
$invoice->items()->updateExistingPivot($key, ['quantity' => $request->quantity]);
}

Magento invoice grid filter_condition_callback not working

I added a custom column to invoice grid using an observer.
The problem is that I can't sort or filter by the new column.
I added a filter condition callback but the function is not called.
Here is my Observer.php
class DB_CustomGrid_Model_Adminhtml_Observer
{
public function onBlockHtmlBefore(Varien_Event_Observer $observer)
{
$block = $observer->getBlock();
$payment_methods = array();
$readConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
$query = 'SELECT method FROM '.Mage::getSingleton('core/resource')->getTableName('sales/order_payment').' GROUP BY method';
$methods = $readConnection->fetchAll($query);
foreach($methods as $payment) {
if($payment["method"] !== 'free') {
$payment_methods[$payment["method"]] = Mage::getStoreConfig('payment/'.$payment["method"].'/title');
}
}
switch ($block->getType()) {
case 'adminhtml/sales_invoice_grid':
$block->addColumnAfter('state', array(
'header' => Mage::helper('sales')->__('Payment Method'),
'index' => 'method',
'type' => 'options',
'width' => '70px',
'options' => $payment_methods,
'filter' => false,
'filter_condition_callback' => array($this, '_myCustomFilter'),
), 'method');
break;
}
}
public function beforeCollectionLoad(Varien_Event_Observer $observer)
{
$collection = $observer->getOrderInvoiceGridCollection();
$collection->join(array('payment'=>'sales/order_payment'),'main_table.order_id=parent_id',array('method'));
}
protected function _myCustomFilter($collection, $column)
{
exit;
if (!$value = $column->getFilter()->getValue()) {
return $collection;
}
$collection->getCollection()->getSelect()->where("sales_order_payment.method like ?", "%$value%");
return $collection;
}
}
I added an exit; to check if the function is called or not.
Try this:
Add a new protected function to your observer class:
protected function _callProtectedMethod($object, $methodName) {
$reflection = new ReflectionClass($object);
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method->invoke($object);
}
Then call $block->sortColumnsByOrder() and the new function $this->_callProtectedMethod($block, '_prepareCollection') directly after $block->addColumnAfter();

can't Filter or search product in grid with custom renderer

I have a problem with filter in my module in admin grid.
I also used 'order_item_id' field in my custom table and fetching product name based on '(sales/order_item)' using renderer.
I also using " 'filter_condition_callback' => array($this, '_productFilter') " but it cant' work
My problem is: can't Filter for columns with custom renderer not working.
When i search product name in column,it returns zero records.
What i wrong in My Code ?
public function _prepareColumns()
{
$this->addColumn('entity_id', array(
'header' => Mage::helper('adminhtml')->__('ID'),
'align' =>'right',
'width' => '50px',
'index' => 'entity_id',
));
$this->addColumn('order_item_id', array(
'header' => Mage::helper('adminhtml')->__('Product Name'),
'align' =>'right',
'index' => 'order_item_id',
'renderer' => 'Test_Module1_Block_Adminhtml_Renderer_Product',
'filter_condition_callback' => array($this, '_productFilter'),
));
return parent::_prepareColumns();
}
protected function _productFilter($collection, $column)
{
if (!$value = $column->getFilter()->getValue()) {
return $this;
}
$this->getCollection()->getSelect()->where(
"order_item_id like ?
"
, "%$value%");
return $this;
}
my renderer is
class Test_Module1_Block_Adminhtml_Renderer_Product extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
public function render(Varien_Object $row)
{
$order = Mage::getModel('sales/order_item')->load($row->getData('order_item_id'));
return $order->getName();
}
}
It is because of you have rendered id and you are searching with product name. So you need to change your productfilter function and put code for search the id in table according to product name.
You need to change your function :
protected function _productFilter($collection, $column)
{
if (!$value = $column->getFilter()->getValue()) {
return $this;
}
$orderitem = Mage::getModel('sales/order_item')->getCollection();
$orderitem->addFieldToFilter('name',array('like'=>'%'.$value.'%'));
$ids =array();
foreach($orderitem as $item){
$ids[] = $item->getId();
}
$this->getCollection()->addFieldToFilter("id",array("in",$ids));
return $this;
}
I have done some changes on saumik code and its work for me.
protected function _productFilter($collection, $column)
{
if (!$value = $column->getFilter()->getValue()) {
return $this;
}
$orderitem = Mage::getModel('sales/order_item')->getCollection();
$orderitem->addFieldToFilter('name',array('like'=>'%'.$value.'%'));
$ids =array();
foreach($orderitem as $item){
$ids[] = $item->getOrderId(); // sales_flat_order_item.order_id = sales_flat_order.entity_id
}
$this->getCollection()->addFieldToFilter("entity_id",array("in",$ids));
return $this;
}

Resources