I'm trying to get this string of tags and iterate through it to get the respective tag's columns on another table:
1A-3,1-1,1-2,3-4,4-6,4-8,6-13,6-15,8-6,8-11,7A-4,7A-5,7A-6
Checks against:
$ministry = AgencyLogin::find(196);
$prefs = $ministry->Ministry_Preferences;
$tags = explode(',', $prefs);
foreach ($tags as $tag) {
$sub_categories[] = DB::table('descriptor')
->where('tag', $tag)
->select('subcategory', 'description')
->first();
}
//dd($sub_categories);
return view('agencydash', compact('sub_categories'));
dd($prefs) prints the correct string. $sub_categories[] never converts to an actual array, so can't be parsed like one, and my limited experience in Laravel means I don't know how to turn a query like this into an array instead the current thing it is, an object.
dd($sub_categories) after I treat it as an object prints a single result which seems to be random:
{#262 ▼
+"subcategory": "SUPPORT ROLE"
+"description": "Project Management"
}
I've been teaching myself Laravel and php steadily, so problems like this open more questions then I can answer yet.
Anybody know what I'm missing?
Why are you iterating through $tags and not using whereIn method and getting a whole collection of relevant rows?
$ministry = AgencyLogin::find(196);
$prefs = $ministry->Ministry_Preferences;
$tags = explode(',', $prefs);
$sub_categories = DB::table('descriptor')
->whereIn('tag', $tags)
->get(['subcategory', 'description']);
//dd($sub_categories);
return view('agencydash', compact('sub_categories'));
Docs
Related
I have a database table with the following structure.
id
setting_name
setting_value
1
website_name
New Website
2
contact_email
info#example.com
3
contact_address
London, UK
Now I am using laravel to return the values of this table,
$syetem_settings = System::all()
This returns it as a collection and there is no way I can use the individual values
$syetem_settings = System::all()->toArray()
This also returns it as an array and foreach loop isn't helping me.
What I want to do
I want to use this variables in the view blade. e.g
{{system_settings->website_name}} // to return website name;
{{system_settings->contact_email}} // to return website email;
Please what is the right code for this? I'm using php 8 and laravel 9
If you really must have this database design, then you would need to get each setting by name from the database as single models, like this:
$websiteName = System::where('setting_name', 'website_name')->first();
$contactEmail = System::where('setting_name', 'contact_email')->first();
Then just output it like this:
{{ $websiteName }}
{{ $contactEmail }}
But if you want to have all the settings variables in one single object, then you would need all the setting_name values as actual columns. So you get ONE single model with all the values instead of one model per value.
This might not be what you want, for other reasons. So a workaround for you, with your current database design, could be something like this:
// Get all rows
$systemSettings = System::all();
// Create empty object
$settingsObject = new stdClass;
// Loop through all the rows (models)
foreach($systemSettings as $systemSetting) {
// Get the settings_name to use as attribute name
$attribute = $systemSetting->setting_name;
// Get the settings_value to use as value for the attribute
$value = $systemSetting->setting_value;
// Add attribute and value to the empty object
$settingsObject->$attribute = $value;
}
This should give you an object called $settingsObject that has all the rows as attribute->value. And then you could output your stuff like this:
{{ $settingsObject->website_name }}
{{ $settingsObject->contact_email }}
I think you're trying to use Entity-Value architecture for your table.
It could be a good idea to pluck each column data separately and then combine them as a single array:
$keys = System::pluck('setting_name')->toArray();
$values = System::pluck('setting_value')->toArray();
$arr = array_combine($keys, $values);
then you can use foreach to itrate through the combined array:
foreach($arr as $k => $v) {
...
}
I have a Laravel site I am modifying, but there are some parts of the PHP code I don't quite understand, which are "array objects" or "object arrays". You see, I don't even know what to call them and so can't find a tutorial or basic data on it. Below is the code that I am dealing with:
private function parseMetric($result, $view)
{
$data = collect([]);
$result->each(function($item) use ($data, $view) {
if (isset($item->metric->{$view})) {
$data->push((object)[
'label' => $item->metric->{$view},
'value' => $item->metric->count
]);
}
});
...
From what I can tell, this creates an object out of $result. If I json_encode this and echo it out I get this:
[{"label":"1k-25k","value":14229},
{"label":"1mm+","value":1281},
{"label":"25k-50k","value":398},
{"label":"50k-75k","value":493},
{"label":"75k-100k","value":3848},
{"label":"100k-150k","value":9921},
{"label":"150k-200k","value":4949},
{"label":"200k-250k","value":3883},
{"label":"250k-300k","value":2685},
{"label":"300k-350k","value":2744},
{"label":"350k-500k","value":4526},
{"label":"500k-1mm","value":8690}]
Now this is obviously an array of arrays... or is it? Is it an array of objects? Or is it an object containing arrays? But the most important question is, how do I access and move or change the individual objects/arrays in this object? For example, I want to take the second object/array, which is:
{"label":"1mm+","value":1281}
and move it to the end. How do I do that? How do I find it? I used the following piece of code to find it which is pretty clunky:
$pos = strpos(json_encode($result), '1mm+');
if($pos){
Log::debug('Enrich 73, I found it!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
And once I find it, how do I move that array/object to the end of the whole object?
And finally, where can I find some kind of tutorial, or documentation, that describes this construct and how to work with it?
There is no need to json_encode the data. Since the data is an instance of Laravel Collection, you can manipulate it like so
$item = $data->firstWhere('label', '1mm+'); // get the item
$data = $data->filter(fn($value, $key) => $value->label !== '1mm+') // remove $item from $data
->push($item); // move $item to the end of data
Acording to Laravel documnentation for Collections, you can try something like this :
To find index of element with name = "1mm+" :
$index = $datas->search(function ($item, $key) {
return $item['name'] == "1mm+";
});
to get an element at a given index :
$element = $datas->get($index);
to Move element at index 3 to the end :
$index = 3
$elementToMove = $data->splice($index, 1);
$datas->push($elementToMove);
Here is a link to the document used : https://laravel.com/docs/8.x/collections
So I have a var_dump($instagram->get_images()); that gives me the following output:
I want to use array_map to map through all the properties and use them inside a foreach loop later on.. but I'm running into some issues:
Here is the attempt that I have:
$mediaUrls = array_map(function($entry) {
return [
'media_url' => $entry['media_url'],
];
}, $instagram->get_images());
I'm getting back the following error:
Could someone assist me on properly array_mapping through the objects and then later be able to use foreach ($MediaUrls as $media) etc...
The error is correct. You're using array map on an object. But the object does have a ->data property that is an array. But the items in the array are objects, so you'll need to refer to their properties rather than using array syntax.
$images = $instagram->get_images();
$mediaUrls = array_map(function($entry) {
return [
'media_url' => $entry->media_url,
];
}, $images->data);
Couple of suggestions. You said, "I want to use array_map to map through all the properties and use them inside a foreach loop later on."
You can reiterate $images->data later on, so I don't really see the value of making another array just for that purpose
foreach ($images->data as $imageData) {
// do something with $imageData->media_url
}
This would be almost exactly the same as iterating the array you're making with array_map.
foreach ($images->data as $imageData) {
// do something with $imageData['media_url']
}
If you want to get an array of just the urls, you can do it more simply with array_column.
$images = $instagram->get_images();
$mediaUrls = array_column($images->data, 'media_url');
(This won't give you the same result. It will be an array of strings rather than an array of arrays.)
I am trying to do a complex search. Lets say for example I have a Book entity with Title & Description properties and it is linked to Tags and Reviewers by many to many relationship.
The closest I can get with a Query is the following:
$qb = $this->createQueryBuilder('b')
->leftJoin('b.tags', 't')
->leftJoin('b.reviewers', 'r');
$ands = $qb->expr()->andX();
// Criteria Check
$ors = $qb->expr()->orX();
$ors->add($qb->expr()->like('b.title', ':criteria'));
$ors->add($qb->expr()->like('b.description', ':criteria'));
$ands->add($ors);
$qb->setParameter('criteria', "%".$criteria."%");
// Tags
$ands->add($qb->expr()->in('t.id', ":tag_var"));
$qb->setParameter("tag_var", [1,2]);
// Reviewers
$ands->add($qb->expr()->in('r.id', ":reviewer_var"));
$qb->setParameter("reviewer_var", [3,4]);
// Add the wheres
$qb->where($ands);
return $qb->getQuery()->getResult();
Which works great if for example a book is linked to least 1 tag but what I am trying to ascertain is how to get the results based if a book has both ids that I have set for the tags?
You mean if all tags must match? I guess you have two separate requirements there, some tags match, or all tags match.
You could simply change the in to an equals for all inclusive.
// All tags must match
$tagValues = [1,2];
foreach ($tagValues as $index => $tag) {
$ands->add($qb->expr()->eq('t.id', ":tag_var_$index"));
$qb->setParameter("tag_var_$index", $tag);
}
Something along those lines should work.
There is gallery on my site, and every picture has own tag. All of the tags are sorting chaotically. I want to sort them by value of field "index" in galleryTagsTable.
When it's show chaotically code was:
foreach ($_tags as $item) {
$select = new Select();
$tags[] = $this->getGalleryTagsTable()->fetchAll($select->where(array('id' => $item)));
}
To make sorting by field "index", I created this field and wrote this code:
foreach ($_tags as $item) {
$select = new Select();
$tags[] = $this->getGalleryTagsTable()->fetchAll($select->where(array('id' => $item))->order('index DESC'));
}
but it still doesn't work. I tried to write without 'DESC' & tried to sort by 'id'. None of these work.
Supposing that your Select() object is some kind of extended object of Zend_Db_Select, I think this is not working as you expected because that's not the correct syntax for the where clause. Correct one would be:
$select->where('id = ?', $item)
->order('index DESC');
Note the '?' wildcard on the expression. This is made in case you don't want it to be an equals but a greater than, or other comparison clauses such as RLIKE. And please, note also that it's not an array.
Probably your where clause wasn't working as intended and that was causing the problems on the order of your tags since they were not grouped by id.
I hope this helps.