1

I'm trying to select multiple columns and avoid duplicate values in these columns with Laravel. Here is my data:

id, name, job, department
[1, "Jane Doe", "worker", "departmentA"]
[2, "Adam Smith", "manager", "departmentB"]
[3, "Machiavelli", "worker", "departmentA"]
[4, "Rousseau", "worker", "departmentC"]

I want to get job and department without duplicate data. So I want this result:

[["worker", "manager"], ["departmentA", "departmentB", "departmentC"]]

I'm trying to get it with model like that:

$users = Users::all();
$user_fields = $users->pluck("job", "department")->toArray();
return $user_fields;

But it's not working. How can I do it?

1
  • 1
    What is "not working"? An error? not the expected result? You cant expect "pluck" to create an array per column... Commented Oct 26, 2021 at 13:10

2 Answers 2

2

I dont think you can do it with one function.

But with two plucks it is simple:

$user_fields = 
    [
        $users->pluck("job")->unique()->values()->toArray(),
        $users->pluck("department")->unique()->values()->toArray()
    ];
Sign up to request clarification or add additional context in comments.

1 Comment

This is the closest answer. Please update your answer with adding values() after the unique() and do not merge arrays, just wrap them with array bracket. That was what I want. Thank you.
0

When you pluck 2 values, you're creating an associative array.

You can split them into separate arrays using array_keys and array_values. I would use array_unique to remove duplicates.

$users = Users::all();

$jobs_despartments = $users->pluck("job", "department")->all();

$jobs = array_unique(array_keys($jobs_despartments));
// ["worker", "manager"]

$departments = array_unique(array_values($jobs_despartments));
// ["departmentA", "departmentB", "departmentC"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.