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?
CodePudding user response:
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()
];
CodePudding user response:
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"]