I am trying to update specific value in my user data.
User data can look like this :
User : {
role : [0, 1],
name : "x",
CommonId : 'xxx',
skills : [
{
id : 1,
name : 'x',
level : 'null'
},
{
id : 2,
name : 'x',
level : 'good
},
.........
]
First, I have to access the specific user who want to make an update ($user) => (working)
Then, i need to access the skills data and found the one to update ($matchedSkill) => (working)
public function UpdateLevelSkill(Request $request)
{
$level = $request->get('level');
$commonId = $request->get('commonId');
$userId = $request->get('userId');
$user = User::where('microsoftId', $userId)->first();
$skills = $user->skills;
$matchedSkill = (object) [];
foreach ($skills as $skill) {
if ($skill['CommonId'] === $commonId) {
$matchedSkill = $skill;
break;
}
};
return response()->json($matchedSkill);
}
When I return matchedSkill
, I got the object skills I want to update.
But then, if I add
$matchedSkill->Level = $level;
$user->save();
I got error:
Attempt to read property "Level" on array"
even if matchedSkill
is an array.
How can I update the skill ?
I have tried to use ['Level']
with no success
I have also tried to add condition (if matchedSkill ...)
2
Answers
Updating with consideration that matchedSkill is an array (working):
One way to improve this code would be to use Laravel’s collection methods for finding the matching skill, which can make the code more readable and concise. For example, we could replace the
foreach
loop with thefirstWhere method:
This way, you can avoid manually looping over the collection and checking for the matching condition.