AndrewMcLagan AndrewMcLagan - 1 year ago 210
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download