how to count the same array value from database in laravel? - arrays

I use Laravel.
I saved the array to the database in the form of a string like this.
enter image description here
Then I want to summarize each piece of data the same. for example "Web Dev" is 5, "Android Dev" is 3.
how to do this? I have used "Has" but the method is undefined.
$summary = [
'byGender' => [
'male' => Member::whereGender('MALE')->count(),
'female'=> Member::whereGender('FEMALE')->count()
],
'bySkill' => [
'WebDev' => Member::expertiseCategoryHas(["Web Dev"])->count(),
'AndroidDev' => Member::expertiseCategoryHas(["Android Dev"])->count(),
'BackendDev' => Member::expertiseCategoryHas(["Backend Dev"])->count()
]
];

I suggest you to save your data to JSON value. Then you can use whereJsonContains() to get desired result.
First, to auto convert your array to json you can do this on your Model:
Model.php
public function setExpertiseCategoriesAttribute($value)
{
$this->attribute['expertise_categories'] = json_encode($value);
}
Then on Controller use whereJsonContains(), for example to count Web Dev:
Model::whereJsonContains('expertise_categories', 'Web Dev')->count();

Related

how to make an laravel 8 API for saving an array of objects

{owner: '456123', holders: Array(2)}
holders:
0: { equipments: 'test', release_by: 'test'}
1: {equipments: 'test', release_by: 'test'}
owner: "456123"
}
i have this kind of array values object from my react formik app and i want to save it into the laravel backend database anybody tell me how to do this one using laravel 8 thanks.
If your json object like this format -
{
owner:456123,
holders: [
{
equipments: 'test',
release_by: 'test'
},
{
equipments: 'test',
release_by: 'test'
}
]
}
This process you can follow.
Create a holder model. This holder model have relation with owner model.
After creating the relationship, you need to create a controller for consume the request. This controller must have a FormRequest for validating your inputs.
In this controller, you can insert your data using batch operation. How to bulk insert in laravel
I think it will help you for farther working process.
I suppose you have the table and have only columns named equipments and release_by other than id (which must be autogenerated) ,created_at and updated_at you can use
table::insert($array) if you have other columns and they are nullable or you have to insert some other values you can use
$newData = new Table;
foreach ($array as $data) {
$newData = new Table;
$newData->equipments => data['equipments'];
$newData->release_by => data['release_by'];
$newData->save();
}

Filter an Array through id and then mapping through a nested array inside

I'm stuck since a while trying to access a nested array inside another array after filtering it by an id. To be clear, this is the mock data I have:
bundleSets: [
{
id: 1,
title: "bundle set 1",
bundles: [
{
bundleTitle: "bundle 1",
content:[]
},
{
bundleTitle: "bundle 2",
content:[]
}
]
},
{ id:2,
title: "bundle set 2",
bundles: [
{bundleTitle: "ciaopao", content:[]}
]
},
{ id:3,
title: "bundle set 3",
bundles: [
{bundleTitle: "ciapo", content:[]}
]
}
]
Now I need to filter each bundleSets by id, and then access the bundles array inside and mapping those elements. This is what I tried to do:
const [key,setKey]=useState(1)
const [bundles,setBundles]=useState([])
useEffect(()=>{
const filteredBundles = bundleSets && bundleSets.filter(bundleSet=>bundleSet.id==key).map(filteredBundles=>{
return filteredBundles.bundles
})
setBundles(filteredBundles)
},[key])
Now If I try mapping the new state I can see on the console.log a weird [Array(1)] instead of the usual [{}] and I can't render it to the page. Where am I getting wrong with this?
Array.prototype.map returns an array and the callback you're passing to the map method returns filteredBundles.bundles which is an array. So, you get an array of arrays. filteredBundles is a confusing name, btw.
Since you're looking up the bundle by id and the ids are unique in the bundleSets array, you can use Array.prototype.find to find the bundle set by id and then get the bundle array. You can return an empty array if find returns undefined (if the key is not found).
const bundles = bundleSets?.find(set => set.id === key)?.bundles || []

Form elements not being submitted

So I've got a weird problem that I'm having a hard time figuring out. I've got a simple form with a few elements that are not being submitted, all of these elements have only one thing in common, they're select elements:
echo $this->Form->control("spirit_type_id", [
"label" => false,
"type" => "select",
"options" => $spirit_types,
"empty" => "Spirit Type"
]);
echo $this->Form->control("country_id", [
"label" => false,
"type" => "select",
"options" => $countries,
"empty" => "Country"
]);
echo $this->Form->control("region_id", [
"label" => false,
"type" => "select",
"options" => $regions,
"empty" => "Region"
]);
And in my controller I have:
public function add() {
$spirit = $this->Spirits->newEntity();
$spirit_types = $this->Spirits->SpiritTypes->find("list");
$countries = $this->Spirits->Countries->find("list");
$regions = $this->Spirits->Regions->find("list");
if ($this->request->is("post")) {
debug($this->request->getData());
die();
$spirit = $this->Spirits->patchEntity($spirit, $this->request->getData());
$spirit->user_id = $this->Auth->user("id");
if ($this->Spirits->save($spirit)) {
$this->Flash->success("Your spirit was successfully saved.");
$this->redirect(["action" => "index"]);
} else {
$this->Flash->error("Your spirit could not be saved.");
}
}
$this->set(compact("spirit", "spirit_types", "countries", "regions"));
}
The important part is that debug statement. It shows this when I insert data using the form.
[
'name' => 'Longrow Peated',
'image' => 'imageLocation',
'brand' => 'Springbank',
'age' => '',
'cost' => '55'
]
Those are all text and/or number elements in my form, and they all come out just fine. It gets a little weirder though. I have validation in my table to require those id fields:
public function validationDefault(Validator $validator) {
$validator->requirePresence(
"name", "brand", "spirit_type_id", "country_id", "region_id", "age", "cost", "image"
)
->notEmpty("name", "We require a name")
->notEmpty("brand", "We require a brand or distillery")
->notEmpty("spirit_type_id", "We require a type of alchohol")
->notEmpty("country_id", "We require a country of origin")
But this doesn't ever seem to get triggered when I insert the data using patchEntity, it's only caught when I actually call the save function and I try inserting into the database.
If $this->request->getData() is not showing all of your fields, the most likely cause would be some sort of problem with your form; there are not a lot of ways for CakePHP to discard your data from here. You can narrow it down by using browser tools (built into most of them now) to inspect the data actually being sent from your browser in the page request.
If it turns out that the fields really aren't being sent across at all, the problem is almost certainly in your form. For example, you might be closing it early, or there might be HTML errors that confuse the browser. Make sure that all of your input tags are between the <form> and </form>, and if they are then try an HTML validator to check your code. There are lots of options online, and even the inspectors built into browsers can often help you spot these sorts of issues.
This is the most common problem:
If you check debug($this->request->getData()); before $spirit = $this->Spirits->newEntity(); you then see all submitted data!
Next go to Spirit Entity and double check if your fields "spirit_type_id,.." accessible!
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* Note that when '*' is set to true, this allows all unspecified fields to
* be mass assigned. For security purposes, it is advised to set '*' to false
* (or remove it), and explicitly make individual fields accessible as needed.
*
* #var array
*/
protected $_accessible = [
'*' => true, // quick fix
'id' => false,
];
or better way:
protected $_accessible = [
'spirit_type_id' => true,
'country_id' => true,
// etc ...
];
Edit
debug
$spirit = $this->Spirits->patchEntity($spirit, $this->request->getData());
debug($spirit); exit();
see if any errors.

Angular2 filtering of array with one property and display the corresponding value

I have a dropdown with list of states which I am getting through services.In JSON I get list of states with id and label. For ex. id:NJ,label:New Jersey. I have a different response coming from backend which gives me id of 5 states-
ex:
"filters": [
{
"name": "listedStates",
"includedCodes": [
"AZ",
"NJ",
"IN",
"OH",
"WI"
]
}
to populate the list of entire US states in the dropdown, I am iterating like this-
this.addressService.getStates().subscribe(
(data) => {
console.log(data);
if (data) {
//filter with filters array
data.states.forEach(i => {
console.log(data.states);
this.newBaseStatesList.push({ 'value': i.id, 'text': i.label });
console.log(this.newBaseStatesList);
});
}
},
(error) => {
//console.log("An error occurred ");
}
);
Right now my dropdown is getting populated with all the state items in the array whereas I would want to display only 5 states in the dropdown mentioned in the filters array. The problem here is the response I am getting from backend has only ids not the labels and the dropdown should contain the labels values. So I have to somehow map these codes with the states array in such a way that these 5 states get filtered and populated.
My object is in format-
{
id:NJ,
label:New Jersey
}
I would like to check with the state codes in filters array with the states array and display the respective labels. Right now, the entire states are getting populated instead of the 5 states mentioned in the filters array.
You can achieve using as below
this.filters.forEach((filter)=>{
filter.includedCodes.forEach((code)=>{
this.newBaseStatesList.push(_.takeWhile(this.data.states, { 'id': code}))'
});
})
Note:I am using Lodash.
I am not sure the syntax that your service returns for the this.data.states so work need to on it based on the sample json

Query data from firebase Array

My firebase users tree has this structure:
users:
{
{
'userName': 'abc',
'userEmail' : 'abc#abc.com',
'userPreferences':
[
0:'Cinema',
1:'It'
]
},
{
'userName': 'abc',
'userEmail' : 'abc#abc.com',
'userPreferences':
[
0:'Cinema',
1:'Music'
]
}
}
Then, I try to find all users that their preference list contain 'Cinema'.
I try this code:
var ref1 = new Firebase("https://event-application.firebaseio.com/users");
$scope.user = $firebaseArray(ref1.orderByChild("userpreferences").equalTo('Cinema'));
console.log($scope.user);
But I don't get the best result. I get this record:
Your JSON structure shows preferences as userPreferences, so wouldn't the following work?
var ref1 = new Firebase("https://event-application.firebaseio.com/users");
$scope.user = $firebaseArray(ref1.orderByChild("userPreferences").equalTo('Cinema'));
console.log($scope.user);
However I think there is also another problem with your code, you're called an .equalTo('Cinema') however you're comparing it to an array, correct me if i'm wrong but I don't think the behaviour of .equalTo('Cinema') is to loop through each of the values and compare them, I think it's just a straight up comparison
If this is the case, you may need to build a custom query by reading the data from firebase and manipulating it via function available to a snapshot
In NoSQL you'll often end up with a data model that reflects the way your application uses the data. If you want to read all the users that have a preference for Cinema, you should model that in your tree:
users: {
'uid-of-abc': {
'userName': 'abc',
'userEmail' : 'abc#abc.com',
'userPreferences': [
0:'Cinema',
1:'It'
]
},
'uid-of-def': {
'userName': 'def',
'userEmail' : 'abc#abc.com',
'userPreferences': [
0:'Cinema',
1:'Music'
]
}
},
"preferences-lookup": {
"Cinema": {
"uid-of-abc": true,
"uid-of-def": true
},
"It": {
"uid-of-abc": true
},
"Music": {
"uid-of-def": true
}
}
Now you can find out what users prefer cinema with:
ref.child('preferences-lookup/Cinema').on('value', function(snapshot) {
snapshot.forEach(function(userKey) {
console.log(userKey.key()+' prefers Cinema');
});
});
This is covered in this blog post on denormalizing data with Firebase, in the Firebase documentation on structuring data and in dozens of answers here on Stack Overflow. A few:
Storing Relational "Type" or "Category" Data in Firebase Without the Need to Update Multiple Locations
Get Firebase items belonging to category
Retrieve data based on categories in Firebase
How to query firebase for property with specific value inside all children

Resources