AndrewMcLagan AndrewMcLagan - 13 days ago 7
PHP Question

Array_unique on a laravel eloquent collection

Not sure if this is possible but im trying to run array_unique over a collection of items i have, to remove duplicates. Although i cannot get it working.

my controller logic:

// init models
$jobs = Job::search();
$countries = $jobs->get()->map(function( $job ) {

return $job->country;
});
$countries = array_unique( $countries->toArray() );


although this gets a "Array to string conversion" error

Answer

You can have unique values in your DB results using distinct or group by in your select clause. But, if you really need to have unique values over an array of object you can do the following:

$uniques = array();
foreach ($countries as $c) {
    $uniques[$c->code] = $c; // Get unique country by code.
}

dd($uniques);