Question

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

Was it helpful?

Solution 3

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

OTHER TIPS

You could try the Unique method of the Collection class:

$countries = $countries->unique();

The Collection class has several wonderful methods. You could read about this in the Laravel API documentation.

I agree that sometimes it is more efficient to "query" on an existing Collection in memory (in stead of doing another query on the database using the Querybuilder class), like for example you first want to count and then filter. In .NET LINQ you can query almost equally on an IEnumerable (in-memory collection) as on a database, something I really enjoy.

I had similar issue and although time have passed since it may be useful to someone today.

The Problem I had was that when I called unique method on collection of items it didn't worked, that is probably the reason the first answer got accepted. So if you have models and you want to remove duplicates based on a specific field you can pass parameter to your unique method, in this case it would be:

$countries->unique('code');

that way you'll only have countries with unique codes. You may notice that only the first value stays, so if you develop a shopping cart application and want for some reason merge carts and only want to have recent items you can just reverse the collection and call unique and reverse it back:

$countries->reverse()->unique('code')->reverse(); // it doesn't really make sense in this example though

it is probably not the best option and it is better to do filtering on the database side but it is nice to have options.

You could try the filter method on eloquent collections if that's exactly what you want to do

http://laravel.com/docs/eloquent#collections

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top