How to get attribute from a collection, with multiple objects inside of an array in Laravel? - laravel

I have a collection that contains an array with 2 objects in it. I'm trying to get the email attribute, right now there are only 2 objects, but there could be 100 objects, so I'm not sure if I need a loop or if I need to use array_merge, or something.
I've attached a screenshot of the data, I'm not showing the attributes, but just know that one of them is email.
I'm die/dumping a variable called $tokens.
In the end, it should return a list of emails, for example:
john.doe#email.com
jane#email.com
thomas.brown#email.com
And I need this logic in the controller, not in the view (.blade), because I'm trying to save this data in a csv file, using fputcsv, that's the main objective and idea here.

Thank you to #jagcweb for the inspiration, his code/answer just needed a couple of tweaks. The following works and does what I was trying to do:
$emails_array = array();
for($i=0; $i <= sizeof($tokens)-1; $i++) {
array_push($emails_array, $tokens[$i]["email"]);
}
Now the $emails_array contains an array with both emails in it.

This sounds like what pluck is for:
$tokens->pluck('email')
Laravel 8.x Docs - Collections - pluck

Related

Laravel Paginate not working with specific model or table

Paginate not working for specific model. with all Models, paginate is working fine except one specific model. Also tried with query builder.
$doubts = DB::table('users')->paginate(10);
dd($doubts->count());
//output: 10
$doubts = DB::table('doubts')->paginate();
dd($doubts->count());
//output: 0
$doubts = DB::table('doubts')->get();
dd($doubts->count());
//output: 8
Don't know what am I missing here. Please help.
Maybe I think you have to put
How many results you want to show per page
So if you want 8
Then I think it should be something like this
$doubts = DB::table('doubts')->paginate(8);
dd($doubts->count());
And if you are using pages Number under your data then you might need the query builder.
You should pass number argument inside paginate function.
Look at laravel pagination documentation
And make sure that DB::table('doubts')
Is returning collection
I thing you must add parameter in paginate(), to show how much data that show per page. You can read documentation in : https://laravel.com/docs/9.x/pagination#paginating-query-builder-results
https://laravel.com/docs/9.x/pagination#cursor-pagination
because you are not add parameter in paginate, it means not data that show every page.
$doubts = DB::table('doubts')->paginate(10);

Effiecient way to get data from database in foreach

I am loading data from excel. In foreach I am checking for each record if it does exist in database:
$recordExists = $this->checkIfExists($record);
function checkIfExists($record) {
$foundRecord = $this->repository->newQuery()
->where(..., $record[...])
->where(..., $record[...])
...
->get();
}
When the excel contains up to 1000 values which is relatively small piece of data - the code runs around 2 minutes. I am guessing this is very inefficient way to do it.
I was thinking of passing the array of loaded data to the method checkIfExists but then I could not query on the data.
What would be a way to proceed?
You can use laravel queue if you want to do a lot of work within a very short time. Your code will run on backend. Client can not recognize the process. just show a message to client that this process is under queue. Thats it
You can check the Official Documentation From Below Url
https://laravel.com/docs/5.8/queues
If you passes all the data from the database to the function (so no more queries to the database), you can use laravel collections functions to filter.
On of them is where => https://laravel.com/docs/5.8/collections#method-where
function checkIfExists($record, Collection $fetchedDataFromDatabase) {
// laravel collectons 'where' function
$foundRecord = $fetchedDataFromDatabase
->where(..., $record[...])
->where(..., $record[...]);
}
other helpful functions.
filter
contains

Magento - Limit selected fields without collection when loading a Model

I know how to limit fields when dealing with a collection, but what I'm wondering is if I can limit the selected fields when using getModel()->load($id).
My thought process is if I know the ID I use:
Mage::getModel('model')->load($id)
as opposed to:
Mage::getModel('model')->getCollection()->addFieldToFilter('id', $id)->getFirstItem();
The issue is load($id) returns everything. I know I can use addFieldToSelect on the collection. Is there an equivalent when using load()? When I google this I get the collection method.
Thanks,
GG
EDIT:
I just want to add that if the collection way is how it's done than that's fine. I just want to make sure it can't be done using load().
No, there is no alternative to use the collection except for rewriting the model code altogether which is probably not what you want to do.
The model load call can only be used to load a full entry - what you can specify is the attribute which to use for the load. For example:
Mage::getModel('catalog/product')->load($sku,'sku')
will load a product by its sku.
In fact the model load itself simply defers to it's resource by doing:
$this->_getResource()->load($this, $id, $field);
But the resource load method does also not provide the ability to filter for specific attributes, so you will always load the full pack or use the collection.
You could try loading a collection with only one item (as you are doing now), and selecting what attributes you want using:
addAttributeToSelect('you_attribute_code_here')
This will return a collection (albeit containing one item), with only the attributes you wish to have returned. Example:
$productIds = array(166);
$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('description')
->addFieldToFilter('entity_id', array('in' => $productIds));
$product = $collection->getFirstItem();

How popular article module is working?

/modules/mod_articles_popular/tmpl/default.php
Can somebody explain me, how this working?
I do not understand how these $item->link and $item->title get correct information?
Where is MySQL query? Is it global variables? If yes, where they are described?
Any advice is much appreciated.
So, like most modules /tmpl/default.php is included on the last line the module entry point file i.e. mod_articles_popular.php
In that file helper.php is included first followed by
$list = modArticlesPopularHelper::getList($params);
As you can see this calls the getList() method of the helper class which performs the task of retrieving the $list of articles.
It (modArticlesPopularHelper) in turn loads the ContentModel and sets the state of the $model based on the default app params and the modules settings.
The it asks the model for the actual items required with the line $items = $model->getItems().
After that it loops through the items returned by the model and creates a link value for each article prior to returning it to the module.
As a result $list is filled with each of the article items which are pulled out individually in the foreach loop in /tmpl/default.php file.

Add new attribute to existing hash

I am retrieving results using Mongoid, but I want to add a new attribute to each of the records returned in an instance variable using the key. How would I go about doing this?
In PHP I would do this by looping through the array and inserting it based on the key of the object. I am unable to figure out how this can be done in Ruby when I receive the message: Model ABC can't be converted into an Integer.
Update: I ended up adding a method in the model to achieve what I was trying to do.
I'll try to point you in the right direction.
If you have an array of records and what to loop through it, use Array#each: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-each
You can write attributes easily: http://rdoc.info/github/mongoid/mongoid/Mongoid/Attributes#write_attribute-instance_method
Hope that helps

Resources