Search code examples
laravellaravel-5.5eloquentlaravel-collection

Using pluck() helper function in laravel


I'm building a small application on laravel 5.5 where I'm getting a list of multiple users with there information, from the forms as below format:

{
    "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"
        }
    ]
}

I just want to get the value key form the users array via laravel collection something like this:

$userIds = $request->users->pluck('value');

so that I can put them into query:

$user = User::all()->whereIn('unique_id', $userIds);

May be I'm doing most of the things wrong but my main motive is to use laravel collection or helper functions and make a cleaner code for this:

$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);

I'm still learning collections, any suggestions is appreciated. Thanks


Solution

  • Data that come from $request (form) isn't a collection. It's an array. If you need it to be collection, you should convert it to collection first.

    PS. If you have multiple DB actions in single method, It's good to have DB transaction.

    \DB::transaction(function () use ($request) {
        // convert it to collection
        $users = collect($request->users);
    
        $team = Team::create([
            'name' => $request->name,
            'description' => $request->description,
            'unique_id' => str_random(),
        ]);
    
        $team->users()->attach($users->pluck('value')->toArray()); 
    });
    
    // HTTP Created is 201 not 200
    return response()->json(['message' => 'Created Successfully'], 201);
    

    or you'll need something like this:

    return \DB::transaction(function () use ($request) {
        $users = collect($request->users);
    
        $team = Team::create([
            'name' => $request->name,
            'description' => $request->description,
            'unique_id' => str_random(),
        ]);
    
        $team->users()->attach($users->pluck('value')->toArray());
    
        return response()->json([
            'message' => 'Created Successfully',
            'data' => $team,
        ], 201); 
    });