我正在构建一个小型应用程序,在该应用程序中laravel 5.5
,我可以从以下格式的表单中获取包含多个用户的信息列表:
{
"name":"Test",
"description":"Test the description",
"users":[
{
"value":"XYZabc123",
"name":"Nitish Kumar",
"email":"nitishkumar@noeticitservices.com"
},
{
"value":"MFnjMdNz2DIzMJJS",
"name":"Rajesh Kumar Sinha",
"email":"rajesh@noeticitservices.com"
}
]
}
我只想通过这样的value
方式从用户数组中获取密钥:laravel collection
$userIds = $request->users->pluck('value');
这样我就可以将它们放入查询中:
$user = User::all()->whereIn('unique_id', $userIds);
可能是我做错了大部分事情,但我的主要动机是使用laravel collection
或helper
功能并为此制作更清晰的代码:
$teamData['name'] = $request->name;
$teamData['description'] = $request->description;
$teamData['unique_id'] = str_random();
$users = $request->users;
$team = Team::create($teamData);
if($team)
{
$userIds = [];
foreach ($users as $user)
{
$getUser = User::where('unique_id', $user['value'])->get()->first();
$userIds [] = $getUser->id;
}
$team->users()->attach($userIds);
return response()->json(['message' => 'Created Successfully'], 200);
}
return response()->json(['message' => 'Something went wrong'], 500);
我还在学习收藏,任何建议都值得赞赏。谢谢