how to delete empty rows in laravel excel? - laravel

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'],
...
]);
}
}
}

Related

INvalid argument foreach laravel when isnsert multiple rows

i want to update status receive to yes after that data also insert to other table multiple rows, i using ajax
this is my controller
public function bulkupdate(Request $request, ItemPR $item_code)
{
if($request->ajax())
{
$item_code = $request->item_code;
$item = ItemPR::whereIn('item_code', explode(",", $item_code))->update(['received'=> 'yes']);
$data = [];
foreach($item as $value){
$data[] = [
'item_code' => $value->item_code,
];
}}
WarehouseInventory::insert($data);
return response()->json(['success'=>"Products Updated successfully."]);
}
but i getting error like this
invalid argument for suplied foreach
how to fix that ?
plis help
thanks

error while update method on boolean

I am trying to update method in Laravel but error is:
"Call to a member function tradereason() on boolean"
I also check same question of other people asked but there're a lot of different in my process. I have lot tables.
let me show you my create code and update method coding.
Create method code:
public function store(Request $request)
{
$tradeID= Auth::user()->trade()->create($input);
$input = $request->all();
$reasons = $request->input('reason');
//Loop for creating KEY as Value
$data = [];
foreach($reasons as $key => $value) {
$data[] = ['reason_id' => $value];
};
if( $data > 0 ) {
foreach ($data as $datum) {
$tradeID->tradereason()->save(new TradeReason($datum));
}
}
}
this is my tring code for update method:
public function update(Request $request, $id)
{
$tradeID= Auth::user()->trade()->whereId($id)->first()->update($input);
$input = $request->all();
$reasons = TradeReason::whereId($id)->first();
$reasons->update($input);
$reasons->tradereason()->sync($request->input('reason'));
$data = [];
foreach($reasons as $key => $value) {
$data[] = ['reason_id' => $value];
};
if( $data > 0 ) {
foreach ($data as $datum) {
$tradeID->tradereason()->whereId($id)->first()->update($datum);
}
}
}
update returns a boolean. So, don't overwrite $tradeID with the results of update.
$tradeID = Auth::user()->trade()->whereId($id)->first();
$tradeID->update($input);
Calling update on the Builder returns an 'int'. Calling update on the Model returns a 'bool'. They don't return Model instances.
// bool
$tradeID= Auth::user()->trade()->whereId($id)->first()->update($input);
The model instance would be what is returned from the first call:
$tradeID = Auth::user()->trade()->whereId($id)->first(); // assuming it finds a record
You can update that, you can use it in the foreach loop.

Laravel change pagination data

My Laravel pagination output is like laravel pagination used to be, but I need to change the data array for each object.
My output is:
As you can see, the data object has 2 items, which I need to change.
My code is:
$items = $this->items()
->where('position', '=', null)
->paginate(15);
Which returns the user items with pivot table, but I don't like the way the pivot table is shown in the JSON, so I decided to change the items and organize each item with the pivot before the item.
For this purpose, I tried to use foreach
foreach ($items->data as $item)
{
}
which giving my an error, for a reason I don't know:
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$data"
status_code: 500
Any help?
The paginator's items is a collection. You can grab it and transform the data like so:
$paginator = $this->items()->where('position', '=', null)->paginate(15);
$paginator->getCollection()->transform(function ($value) {
// Your code here
return $value;
});
If you are familiar with tap helper here is the snippet that does exact same.
$paginator = tap($this->items()->where('position', '=', null)->paginate(15),function($paginatedInstance){
return $paginatedInstance->getCollection()->transform(function ($value) {
return $value;
});
});
We can't chain method getCollection to paginator instance because AbstractPaginator will return paginator's underlying collection. so the paginator instance will be transformed to Collection. So fix that we can use tap helper.
If you'd like to keep items paginated:
$itemsPaginated = $this->items()
->paginate(15);
$itemsTransformed = $itemsPaginated
->getCollection()
->map(function($item) {
return [
'id' => $item->id,
];
})->toArray();
$itemsTransformedAndPaginated = new \Illuminate\Pagination\LengthAwarePaginator(
$itemsTransformed,
$itemsPaginated->total(),
$itemsPaginated->perPage(),
$itemsPaginated->currentPage(), [
'path' => \Request::url(),
'query' => [
'page' => $itemsPaginated->currentPage()
]
]
);
There is a setCollection method for such purpose.
$items = Model::paginate(10);
$updatedItems = $items->getCollection();
// data manipulation
// ...
$items->setCollection($updateItems);
From the source code of /Illuminate/Pagination/AbstractPaginator.php
/**
* Set the paginator's underlying collection.
*
* #param \Illuminate\Support\Collection $collection
* #return $this
*/
public function setCollection(Collection $collection)
{
$this->items = $collection;
return $this;
}
Source
I could make shorter way. This returns edited $array instead of simple $paginated. This example modify file names.
This doc was useful for me.
$paginated=$query->paginate(12);
$array=$paginated->toArray();
foreach ($array['data'] as $r=>$record) {
$array['data'][$r]->gif=$array['data'][$r]->gif.".gif";
}
return $array;
Sample Example :
$franchiseData=[ 'id'=>1 ,'name'=>'PAnkaj'];
$models = $bookingsQuery->paginate(10);
$models->setCollection(collect($franchiseData));
return $models;
Note that $models->setCollection(collect($franchiseData)); you have to use collect() else you will get error.
getCollection
is one way to get the items. Another way is to use this
For ex- Assuming, user doesn't have name param and only have first_name and last_name
$userPaginatedData = User::paginate(15);
$users = $userPaginatedData->items();
foreach($users as $user) {
$user->name = $user->first_name . ' ' . $user->last_name;
}
return $userPaginatedData;
Now in the data key, you would see that each user has name param with it.
Laravel 8.9.0 has added the through method to AbstractPaginator.
It transforms each item in the slice of items using a callback, and keeps the items paginated.
$paginator = $this->items()->where('position', '=', null)->paginate(15);
$paginator->through(function ($value) {
// Your code here
return $value;
});
The source code:
/**
* Transform each item in the slice of items using a callback.
*
* #param callable $callback
* #return $this
*/
public function through(callable $callback)
{
$this->items->transform($callback);
return $this;
}
-Laravel 5.4
// example update column "photo"
// from "/path/to/photo.png"
// to "abc.com/path/to/photo.png"
foreach ($items as $item)
{
$path = $item->photo;
// Remove
$item->offsetUnset("photo");
// Set
$item->offsetSet("photo", url($path));
}
Laravel AbstractPaginator has methods setCollection() and getCollection()
<?php
$itemsPaginated = $this->items()->paginate(15);
$itemsPaginated->setCollection(
$itemsPaginated->getCollection()->transform(function ($item) {
// Your code here
return $item;
})
)
This is your paginated items...
$items = $this->items()
->where('position', '=', null)
->paginate(15);
I am using Laravel 8, can simply use each
$items->each(function ($item) {
// your code here
$item->custom_data = calcSomeData(); // sample
});
It does the same as this...
$items->getCollection()->transform(function ($item) {
// your code here
$item->custom_data = calcSomeData(); // sample
});
<?php
$itemsPaginated = $this->items()->paginate(15);
$itemsPaginated = json_encode($itemsPaginated);
foreach ($itemsPaginated->data as $key => $item) {
$results->data[$key]; //Modify
}
$itemsPaginated = json_encode($results);
you have to use below code in your blade
{!! $items->render() !!}
Ignore the pagination in laravel and hit the normal data
foreach ($items as $item)
{
}

Rewriting AutoSuggest (Minisearch) of Magento

I been trying for hours now to successfully rewrite Magento's build-in Autosuggest Function so it displays productnames instead of query history entries. I want nothing fancy, no product pictures and whatnot, just plain product name suggestions.
So to get the productnames, I created under app/code/local/Aw the folder CatalogSearch/Model and there created a file named Query.php. Inside that file I have the following class and rewritten method:
class Aw_CatalogSearch_Model_Query
extends Mage_CatalogSearch_Model_Query {
public function getSuggestCollection() {
$collection = $this->getData('suggest_collection');
if (is_null($collection)) {
$collection = Mage::getModel('catalog/product');
Mage::getSingleton('catalog/product_status')
->addVisibleFilterToCollection($collection);
$collection->getCollection()
->addAttributeToSelect('name')
->addAttributeToFilter('name', array('like' =>
'%'.$this->getQueryText().'%'))
->addExpressionAttributeToSelect('query_text', '{{name}}', 'name')
->addAttributeToSort('name', 'ASC')
->setPageSize(10)
->addStoreFilter($this->getStoreId());
$this->setData('suggest_collection', $collection);
}
return $collection;
}
};
I created the module xml file in app/etc/modules/ and the module configuration in app/code/local/Aw/CatalogSearch/etc/config.xml
All good so far, the overwritten method getSuggestCollection() is executed.
The problem comes in app/code/core/Mage/CatalogSearch/Block/Autocomplete.php, in the getSuggestData() method.
public function getSuggestData()
{
if (!$this->_suggestData) {
$collection = $this->helper('catalogsearch')->getSuggestCollection();
$query = $this->helper('catalogsearch')->getQueryText();
$counter = 0;
$data = array();
foreach ($collection as $item) {
$_data = array(
'title' => $item->getQueryText(),
'row_class' => (++$counter)%2?'odd':'even',
'num_of_results' => $item->getNumResults()
);
if ($item->getQueryText() == $query) {
array_unshift($data, $_data);
}
else {
$data[] = $_data;
}
}
$this->_suggestData = $data;
}
return $this->_suggestData;
}
When it iterates over the collection, I get a
Call to a member function getQueryText() on a non-object ...
The point I do not understand is that I have defined an alias field named 'query_text' in the collection query inside the getSuggestCollection() method. Even when I used something like getData('query_text') or $item->getQuery_text() to get the data of this field is not working.
I have the strong feeling, that the collection object is not valid as it supposed be within the getSuggestData() method of Mage_CatalogSearch_Block_Autocomplete class.
Can anybody point me out how to solve this issue? Is it not possible as above way to gather suggestions from the products collection and pass these to Autocomplete.php?
This is my first magento project, so please bear with me! I am really lost on this one!
Any hint is greatly apprecitated.
Using Magento 1.7.0.2 for this project.
Well, I found a solution. For anyone who might be interested in this, the problem stated in my question is located in the following lines
$collection = Mage::getModel('catalog/product');
Mage::getSingleton('catalog/product_status')
->addVisibleFilterToCollection($collection);
$collection->getCollection() ... // continue method chaining ...
I changed the code, so that the constructor and methods are chained all together, like this:
$collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('name') ... // continue method chaining
...
I added the filters for product_status, cataloginventory/stock and catalog/product_visibility with singleton calls right after the collection is available
In that way, everything works as expected.
For anyone else wanting to do something similar, I just rewrote app/code/core/Mage/CatalogSearch/Block/Autocomplete.php to my own module and made the search results query the sku and return product names. Your mileage may vary, however, my sku codes are sensible names rather than random digits so this worked for me.
public function getSuggestData()
{
if (!$this->_suggestData) {
$collection = $this->helper('catalogsearch')->getSuggestCollection();
$query = $this->helper('catalogsearch')->getQueryText();
$counter = 0;
$data = array();
foreach ($collection as $item) {
$_data = array(
'title' => $item->getQueryText(),
'row_class' => (++$counter)%2?'odd':'even',
'num_of_results' => $item->getNumResults()
);
if ($item->getQueryText() == $query) {
array_unshift($data, $_data);
}
else {
$data[] = $_data;
}
}
// Get products where the url matches the query in some meaningful way
$products = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('name')
->addAttributeToFilter('type_id', 'configurable')
->addAttributeToFilter('sku',array('like'=>'%'.$query.'%'))
->load();
foreach($products as $product) {
$_data = array(
'title' => $product->getName(),
'row_class' => (++$counter)%2?'odd':'even',
'num_of_results' => 1
);
// if ($item->Name() == $query) {
// array_unshift($data, $_data);
// }
// else {
$data[] = $_data;
// }
}
$this->_suggestData = $data;
}
return $this->_suggestData;
}
I did not need to rewrite Mage_CatalogSearch_Model_Query, just the code for the suggestions.

codeigniter view, add, update and delete

I'm newbie in codeigniter and still learning. Anyone can help for sample in basic view, add, update, delete operation and queries in codeigniter will gladly appreciated.
Just a simple one like creating addressbook for newbie.
thanks,
best regards
Some sample queries in Codeigniter
class Names extends Model {
function addRecord($yourname) {
$this->db->set("name", $yourname);
$this->db->insert("names");
return $this->db->_error_number(); // return the error occurred in last query
}
function updateRecord($yourname) {
$this->db->set("name", $yourname);
$this->db->update("names");
}
function deleteRecord($yourname) {
$this->db->where("name", $yourname);
$this->db->delete("names");
}
function selectRecord($yourname) {
$this->db->select("name, name_id");
$this->db->from("names");
$this->db->where("name", $yourname);
$query = $this->db->get();
return $this->db->result();
}
function selectAll() {
$this->db->select("name");
$this->db->from("names");
return $this->db->get();
}
}
More information and more ways for CRUD in codeigniter active record documentation
More about error number over here
A sample controller
class names_controller extends Controller {
function addPerson() {
$this->load->Model("Names");
$name = $this->input->post("name"); // get the data from a form submit
$name = $this->xss->clean();
$error = $this->Names->addRecord($name);
if(!$error) {
$results = $this->Names->selectAll();
$data['names'] = $results->result();
$this->load->view("show_names", $data);
} else {
$this->load->view("error");
}
}
}
More about controllers over here
A sample view - show_names.php
<table>
<tr>
<td>Name</td>
</tr>
<?php foreach($names as $row): ?>
<tr><td><?ph echo $row->name; ?></td></tr>
<?php endforeach; ?>
</table>
More about codeigniter views over here
You can use this as an example
class Crud extends Model {
// selecting records by specifying the column field
function select()
{
// use $this->db->select('*') if you want to select all the records
$this->db->select('title, content, date');
// use $this->db->where('id', 1) if you want to specify what row to be fetched
$q = $this->db->get('mytable');
// to get the result
$data = array();
// for me its better to check if there are records that are fetched
if($q->num_rows() > 0) {
// by doing this it means you are returning array of records
foreach($q->result_array() as $row) {
$data[] = $row;
}
// if your expecting only one record will be fetched from the table
// use $row = $q->row();
// then return $row;
}
return $data;
}
// to add record
function add()
{
$data = array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
);
$this->db->insert('mytable', $data);
}
// to update record
function update()
{
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', 1);
$this->db->update('mytable', $data);
}
// to delete a record
function delete()
{
$this->db->where('id', 1);
$this->db->delete('mytable');
}
}
Some of this are from codeigniter userguide.
To view the records,
If return data is array of records,
foreach($data as $row)
{
echo $row['title'] . "<br />";
}
If the return data is an object (by using $q->row),
echo $data->title;
This is just a few examples or CRUD in Codeigniter. Visit the codeigniter userguide.

Resources