Trying to implement a search box in codeigniter - ajax

Query not working:
$attributes is an array which contains field names
public function search($table,$like,$attributes){
foreach ($attributes as $key => $attribute) {
$query = $this->db->query("SELECT * FROM $table WHERE $attribute LIKE '$like%'");
echo $this->db->last_query();
}
}

Related

get all data count from relationship | Laravel

i use laravel:command for function, which is i need to know how many reviews been given to my products, i will capture my database example below:
Product fields
Reviews fields
i've already declare the relationship which is:
App\Models\Product :
public function rev()
{
return $this->hasMany(Reviews::class, 'product_id', 'id');
}
App\Models\Review :
public function prod()
{
return $this->belongsTo(Products::class, 'product_id','id');
}
and this is my command for the function:
protected $signature = 'review:product {product_id}';
public function handle()
{
$id = $this->arguments('product_id');
$products = Products::with('rev')->whereId($id)->get();
foreach ($products as $key => $value) {
$rating = $value->rev->rating;
}
dd($products);
}
after i run my command it returns this error
Error
what i'm expecting is i could get the whole rating of specific id
You did not declare the variable $rating prior to using it.
But there is a much easier approach to your problem, since youve already setup the relationships.
public function handle()
{
$id = $this->arguments('product_id');
$products = Products::find($id);
$ratings = $products->rev->pluck('rating');
dd($ratings);
}
Because of product can have many revs, so you can use loop for this
foreach ($value->rev as $item) {
$val = $item->rating;
}
if you are expecting to sum up all rating for particular product id, then you should declare initial number for variable $rating before foreach, then sum up with += operator :
public function handle(){
$id = $this->arguments('product_id');
$products = Products::with('rev')->whereId($id)->get();
$rating = 0;
foreach ($products as $key => $value) {
$rating += $value->rev->rating;
}
dd($rating);
}

how to show unix timestamp in blade view from created_at or updated_at field in database laravel?

I want to get UNIX timestamp or convert created_at or updated_at date to UNIX timestamp format from database fields (created_at and updated_at) in laravel 5.8 , how can i do this?
this is my code in my controller :
public function viewArchives(){
$data = Archive::select(‘created_at’)->get();
return view(‘view.archives’, compact(‘data’));
}
and in view/archives.blade.php :
<?php echo $data;?>
the result is :
{“created_at”:”2019-03-17 19:10:30″}
but i want the result be like this :
{“created_at”:”1552849830″}
how can get this result?
$string = '2019-03-17 19:10:30';
$obj = new stdClass;
$obj->created_at = $string;
$collection = [$obj];
foreach ($collection as $k => &$v) {
$collection[$k]->created_at = strtotime($v->created_at);
}
//var_dump($collection);
or
$string = '2019-03-17 19:10:30';
$obj = new stdClass;
$obj->created_at = $string;
$collection = [$obj];
array_walk($collection, function (&$item, $key) {
$item->created_at = strtotime($item->created_at);
});
//var_dump($collection);
Or in your case
public function viewArchives()
{
$data = Archive::select('created_at')->get();
foreach ($data as $k => &$v) {
$v->created_at = strtotime($v->created_at);
}
return view('view.archives', compact('data'));
}
or
public function viewArchives()
{
$data = Archive::select('created_at')->get();
array_walk($data, function (&$item, $key) {
$item->created_at = strtotime($item->created_at);
});
return view('view.archives', compact('data'));
}
This is good place to use array_walk() function.
Add strtotime() view/archives.blade.php :
<?php echo strtotime( $data );?>
With an Eloquent Model one can actually define the $casts per column:
class SomeModel extends Model
{
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'created_at' => 'datetime'
];
}
If you want epoch timestamps instead, just remove this cast (which is likely present).
When the timestamp isn't from any Eloquent Model, one still can render it with Blade:
#php
$dt = new DateTime();
echo $dt->setTimestamp( $timestamp )->format("Y-m-d H:m:s");
#endphp
Or the other way around:
#php
echo strtotime( $isodate );
#endphp

how to delete empty rows in laravel excel?

So i work with Laravel, and i use Laravel excel to load excel/csv files, but my files contains empty rows and i want to delete every empty row.
this is my code :
Excel::selectSheetsByIndex(0)->load($path, function($reader){
$results = $reader->noHeading()->toArray();
foreach ($results as $row) {
//my code
}
}, 'UTF-8');
So please if someone has any idea how i can do that i will be very appreciative
I think you can do it in this way
/** #var LaravelExcelReader $data */
$data = \Excel::load('file.xls', function ($reader) {
$reader->limitRows(20);
$reader->ignoreEmpty();
})->get()->toArray();
# remove empty rows
$data = array_filter($data);
use ToCollection method the wrap everything within if($row->filter()->isNotEmpty())
public function collection(Collection $rows)
{
foreach($rows as $row) {
if($row->filter()->isNotEmpty()){
// you logic can go here
$user = User::create([
'name' => ucwords($row['name']),
'class' => $row['class'],
...
]);
}
}
}

How can I use CodeIgniter form dropdown function?

codeIgniter form_dropdown() function can receive only associative array but I have multi dimension array by using result_array() function. How can I fetch my data on form_dropdown() function?
Let's say you want a dropdown of items, using result_array():
$query = $this->db->query("SELECT id, item_name FROM items");
$options = array();
foreach ($query->result_array() as $row){
$options[$row['id']] = $row['item_name'];
}
echo form_dropdown('my_items_dropdown', $options, '1');
I have extended the class DB_result.php in system/database with this new function
public function dropdown_array($id_field = FALSE, $list_field = FALSE)
{
$result = array();
if ($id_field === FALSE || $list_field === FALSE) return $result;
$array = $this->result_array();
foreach ($array as $value) {
$result[$value[$id_field]] = $value[$list_field];
}
return $result;
}
Now you can simply call from every Model class your new function to generate a dropdown-compliant array like this:
$customers = $this->db->get('customers');
$result = $customers->dropdown_array('id', 'name');
return $result;

Get all manufacturers for a particular store

The following code gets me all the manufacturers in all my stores:
$attribute = Mage::getSingleton('eav/config')->addStoreFilter($storeId)->getAttribute('catalog_product', 'manufacturer');
if ($attribute->usesSource()) {
$options = $attribute->getSource()->getAllOptions(false);
}
However I have multiple stores and I only want the manufacturers for my chosen store id.
I've tried adding store filters to this but with no luck.
Any one have any ideas how to filter this by store?
$product = Mage::getModel('catalog/product');
$storeId = Mage::app()->getStore()->getId();
$attributes = Mage::getResourceModel('eav/entity_attribute_collection')
->setStoreId($storeId);
->setEntityTypeFilter($product->getResource()->getTypeId())
->addFieldToFilter('attribute_code', 'manufacturer') // This can be changed to any attribute code
->load(false);
$attribute = $attributes->getFirstItem()->setEntity($product->getResource());
/* #var $attribute Mage_Eav_Model_Entity_Attribute */
$manufacturers = $attribute->getSource()->getAllOptions(false);
return $manufacturers;
This should do it. You can lower the attribute to select on.
$product = Mage::getModel('catalog/product');
$products = $product->setStoreId($storeId)->getCollection()
->addAttributeToSelect(array('name', 'price', 'small_image','short_description','manufacturer'), 'inner');
$this->setProductCollection($products);
See this blog post: http://www.sharpdotinc.com/mdost/2009/04/06/magento-getting-product-attributes-values-and-labels/
Go to the section labled "How to get Only the Attribute Values that have been used on products"
I got the list of manufacturer from the current store using product count
public function getAllManu()
{
$product = Mage::getModel('catalog/product');
$attributes = Mage::getResourceModel('eav/entity_attribute_collection')
->setEntityTypeFilter($product->getResource()->getTypeId())
->addFieldToFilter('attribute_code', 'manufacturer'); //can be changed to any attribute
$attribute = $attributes->getFirstItem()->setEntity($product->getResource());
$attrMenuItems = $attribute->getSource()->getAllOptions(false);
foreach ($attrMenuItems as $key => $value) {
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addFieldToFilter(array(array('attribute' => 'manufacturer', 'eq' => $value['value'])));
$numberOfProducts = count($collection);
$attrMenuItems[$key]['products_count'] = $numberOfProducts;
}
return $attrMenuItems;
}

Resources