insert data into laravel 5 blade from array - laravel-5

I'm puzzled over this one..
I have an array of arrays that I'm passing into a blade from a controller
data looks like this
(
[0] => Array
(
[id] => 1
[name] => AAAA
)
[1] => Array
(
[id] => 2
[name] => BBBB
)
[2] => Array
(
[id] => 3
[name] => CCCC
)
[3] => Array
(
[id] => 4
[name] => DDDD
)
)
The controller passes it by calling the view as such
return view('items.pivot', compact('sites'));
and I attempt to display it in the blade like
#foreach($sites as $site)
#if($site != '' || $site != null)
<th class="col1" >{{$site->name}}</th>
#endif
#endforeach
However what I get is the correct number of columns, but with each looking like
<th class="col1" ></th>
What am I doing wrong? I know it must be obvious.. but I can't see it..

You're treating it like an object, while it's an array that you fed into view.
So change your code from $site->name to $site['name']

It is an array and you are treating it as an object. Replace {{$site->name}} with {{$site['name']}}

Related

How to loop collection without looping inside each item?

I have a collection. For each item I want to add a new attribute [users]. When I loop collection with map function or even if foreach, I notice, the code is looping inside each item. So each atribute from collection item is read. Please look at this following
Log $myCollection:
local.INFO: Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => Array
(
[id] => 6
[name] => AAAAA
[code] => D2
[component_id] => 5
)
[1] => Array
(
[id] => 7
[name] => BBBB
[code] => D1
[component_id] => 5
)
[2] => Array
(
[id] => 47
[name] => CCCC
[code] => CR7
[component_id] => 3
)
[3] => Array
(
[id] => 48
[name] => DDDD
[code] => CJ9
[component_id] => 3
)
)
)
$myCollection->map(function ($item) use($users, $role) {
$item = Site::findOrFail($item);
$item->users = $users;
return $item;
});
I get :
SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: "AAAA". and I think it is because the code loops on name from each item of myCollection.
How do I fix it, please? thanks
The $item contains each object of the collection so you should use the appropriate key.
$myCollection->map(function ($item) use($users, $role) {
$item = Site::findOrFail($item->id); // or $item['id']
$item->users = $users;
return $item;
});
Actually now that I looked at it better, you don't need at all to find the item again. So in your closure just having these two lines is enough.
$item->users = $users;
return $item;

Getting count of occurrences in Laravel

I have a backend where I can create a Poll. Within a Poll I can create a PollQuestion. And for a PollQuestion, I can create many PollAnswer's.
If I do something like this in my Controller
$poll = DB::table('poll')->orderBy('id', 'desc')->first();
$question = DB::table('poll_question')->where('poll_id', $poll->id)->first();
$answers = DB::table('poll_answer')->select('answer')->where('question_id', $question->id)->get();
print_r("<pre>");
print_r($answers);
print_r("</pre>");
I can see an output like the following
Array
(
[0] => stdClass Object
(
[answer] => Answer 1
)
[1] => stdClass Object
(
[answer] => Answer 2
)
[2] => stdClass Object
(
[answer] => Answer 3
)
[3] => stdClass Object
(
[answer] => Answer 4
)
)
So, the above Poll was given 4 possible answers to the PollQuestion.
Now I have a frontend which displays the question, and a radio button for each PollAnswer. When they select one and save, I get a PollResponse. If I do something like this
$pollResponses = DB::table('poll_response')->select('response')->where('poll_id', $poll->id)->get();
The output might be something like this
Array
(
[0] => stdClass Object
(
[response] => Answer 1
)
[1] => stdClass Object
(
[response] => Answer 4
)
[2] => stdClass Object
(
[response] => Answer 4
)
[3] => stdClass Object
(
[response] => Answer 2
)
[4] => stdClass Object
(
[response] => Answer 3
)
)
So I can see what people have selected. Now, for each possible PollAnswer, I need to count the number of PollResponse which relate to it. So for the above data, I should get something like
1 = 1
2 = 1
3 = 1
4 = 3
Is there any easy way I can do this in Laravel, or would I need to loop both the Answers and Responses to get the individual counts?
I don't know of any laravel-specific solution, but you can always push the responses to a separate array and then use the php function array_count_values($array) (http://php.net/manual/en/function.array-count-values.php) on the new array.
$newArray = array();
for($i=0; $i < count($pollResponses); $i++){
array_push($newArray, $pollResponses[$i]->response);
};
$count = array_count_values($newArray);
It will return a two dimensional array with the answer as the key and the number of times it occurs as the value.
Assuming that you're using models,you can do this in Laravel
$polls = Poll::with(['questions.answers'])->get();
Your Poll.php file
...
class Poll extends Model{
public function questions(){
return $this->hasMany(Question::class);
}
}
Your Question.php file
...
class Question extends Model{
public function answers(){
return $this->hasMany(Answer::class);
}
}
And then in your view file (assuming it's .blade.php)
#foreach($polls as $poll)
#foreach($poll->questions as $question)
{{ $question->title }}
<ul>
#foreach($question->answers as $answer)
<li>{{ $answer->title }} </li>
#endforeach
</ul>
#endforeach
#endforeach

Laravel: nested "with()" function

I want to retrieve data from three tables: courses, competencies and competency_standards. The following query almost works, but it does not bring back the associated competency_standards table data.
$coursesAndComps = Course::with(
array('competencies' => function($query)
{
Competency::with('competency_standards');
})
)->get()->toArray();
Where the competencies table is linked to the courses table (competencies.course_id = course.id) and the competency_standards table links to the competencies table (competency_standards.competencey_id = competency.id).
The array returned looks like this:
Array
(
[0] => Array
(
[id] => 1
[name] => the first course
[competencies] => Array
(
[0] => Array
(
[id] => 9
[course_id] => 1
[name] => first course comp 1
)
[1] => Array
(
[id] => 10
[course_id] => 1
[name] => first course comp 2
)
)
)
)
but within the competencies array, I was hoping to find another array called competency_standards like this:
...
[0] => Array
(
[id] => 9
[course_id] => 1
[name] => first course comp 1
[competency_standards] => Array
(
[0] => Array
(
[id] => 22
[competency_id] => 9
[name] => standard foo
)
[1] => Array
(
[id] => 23
[competency_id] => 9
[name] => standard bar
)
)
)
...
Is this possible? Am I going about this the wrong way?
It should be possible to use:
$coursesAndComps = Course::with('competencies', 'competencies.standards')
->get()->toArray();
but of course you need to have defined standards relationship in Competency model to link Competency with Standard

how to get the values of multidimensional array

how to get the values of multidimensional array.
code//
Array
(
[0] => Array
(
[City] => Array
(
[title] => Nagpur
[id] => 20299
)
[Branch] => Array
(
[0] => Array
(
[id] => 8
[country_id] => 41
[state_id] => 102
[city_id] => 20299
[title] => Geotech Services Ltd.
)
)
)
[1] => Array
(
[City] => Array
(
[title] => kolapur
[id] => 20300
)
)
)
Here I want to get the only values if cities(title) so plz tel me how to fetch in cakephp..
Thanks in advance
Thus you finding as recursive so all related data is fetched with City.
To disable this recursion, you need to set $recursive = -1;
You can do this by many ways--
place $this->City->recursive = -1; before find operation
place recursive => -1 on find overation
Globally set public $recursive = -1; on AppModel.php
And if you read from this array its simple and basic programming operation...
foreach($cities as $city){
echo $city['City']['title']
}
using cakePHP what you're trying to do is usually achieved using Hash
Assuming $your_array contains the data, then you have to do:
$cities = Hash::extract($your_array, '{n}.City.title');

Getting a list of magento stores

How can I get a list of store groups under a website in Magento and then a list of stores from that store group?
Try this to get the objects directly
Mage::app()->getWebsites(); < in file > app/code/core/Mage/Core/Model/App.php:920
Mage::app()->getStores(); < in file > app/code/core/Mage/Core/Model/App.php:834
iterate over to get the needed scope of one specific website or store
foreach (Mage::app()->getWebsites() as $website) {
foreach ($website->getGroups() as $group) {
$stores = $group->getStores();
foreach ($stores as $store) {
//$store is a store object
}
}
}
For the future if you have similar questions here's how i discovered those answers within 60 seconds. First i grep for method names or similar method names with space before method name to see where the methods are defined
grep ' getStores' app/code -rsn
grep ' getWebsites' app/code -rsn
Second step is grep for usage samples to see how they are meant to use by core developers. For that i add >methodName to grep and this gives me list of files where this method is called and this will give us place to look for examples:
grep '>getWebsites' app/code -rsn
Anton's answer, while correct, may be re-inventing the wheel just a bit. There is already a facility in the Magento Core to retrieve this sort of data.
You can retrieve a list of all websites, and their "children" using this:
Mage::getSingleton('adminhtml/system_store')->getStoresStructure()
You can also pass an array of websiteIds, storeIds, or storeGroupIds to the function, to filter the list:
public function getStoresStructure($isAll = false, $storeIds = array(), $groupIds = array(), $websiteIds = array())
Example output:
Array
(
[1] => Array
(
[value] => 1
[label] => Main Website
[children] => Array
(
[1] => Array
(
[value] => 1
[label] => Madison Island
[children] => Array
(
[1] => Array
(
[value] => 1
[label] => English
)
[2] => Array
(
[value] => 2
[label] => French
)
[3] => Array
(
[value] => 3
[label] => German
)
)
)
)
)
)
There is a similar one used to populate the "Store Scope" dropdowns and multi-selects all across the admin section.
Mage::getSingleton('adminhtml/system_store')->getStoreValuesForForm(false, true)
Array
(
[0] => Array
(
[label] => All Store Views
[value] => 0
)
[1] => Array
(
[label] => Main Website
[value] => Array
(
)
)
[2] => Array
(
[label] => Madison Island
[value] => Array
(
[0] => Array
(
[label] => English
[value] => 1
)
[1] => Array
(
[label] => French
[value] => 2
)
[2] => Array
(
[label] => German
[value] => 3
)
)
)
)
To discover this, I located a multi-select on the Admin that has the data I wanted, then I turned on template hints to find out which block class was responsible for rendering it: Mage_Adminhtml_Block_Cms_Page_Edit_Form. Knowing this, I found the class in the codebase,(app/code/core/Mage/Adminhtml/Block/Cms/Block/Edit/Form.php) and located the part that creates the input by searching for its label ("Store View"). This showed me how the input's values were being provided:
$field =$fieldset->addField('store_id', 'multiselect', array(
'name' => 'stores[]',
'label' => Mage::helper('cms')->__('Store View'),
'title' => Mage::helper('cms')->__('Store View'),
'required' => true,
'values' => Mage::getSingleton('adminhtml/system_store')->getStoreValuesForForm(false, true),
));
The Mage::getSingleton('adminhtml/system_store') points to the class Mage_Adminhtml_Model_System_Store, where I found a variety of similar methods that can also be useful. Have a look for yourself.

Resources