Anil Meena
Anil Meena

Reputation: 33

Laravel remove objects with duplicate values in array

My application returns an array of objects and each object contains a "name" key which sometimes is repeated in other objects.

How can I filter the duplicates?

This is an array having duplicates

[
    {"name":"India","id":2,"uid":"1M16"},
    {"name":"Delhi","id":3,"uid":"1M16"},
    {"name":"India","id":4,"uid":"1M16"}
]

The output I want is:

[
    {"name":"India","id":2,"uid":"1M16"},
    {"name":"Delhi","id":3,"uid":"1M16"}
]

And this is how I am getting this array from database.

$results_1 = Sheet::whereIn('uid', $results_1)->select('name', 'id', 'uid')->get(); 

Upvotes: 1

Views: 968

Answers (2)

Sabaoon Bedar
Sabaoon Bedar

Reputation: 3689

If you worried to change the modes in config/database.php which could be risky for all queries you are accessing through laravel you can simply one line above to the specific query where you want to off the strict mode. This answer will help those who are in search to do it without changing the modes globally.

Like this:

DB::statement("SET SQL_MODE=''");//this is the trick use it just before your query
$results_2 = Sheet::whereIn('uid', $results_1)->select('name', 'id', 'uid')->groupBy('name')->get();

Upvotes: 0

zahid hasan emon
zahid hasan emon

Reputation: 6233

You can use distinct() if you want a single column. In your case you need groupBy() to get the unique values.

$results_2 = Sheet::whereIn('uid', $results_1)->select('name', 'id', 'uid')->groupBy('name')->get();

you are using same $results_1 variable to hold the new values and in whereIn clause. consider using different variables.

And to use groupBy() you have to change some things in your database config file. in your config>database.php file add this lines in mysql configuration.

'modes' => [

    'STRICT_TRANS_TABLES',
    'NO_ZERO_IN_DATE',
    'NO_ZERO_DATE',
    'ERROR_FOR_DIVISION_BY_ZERO',
    'NO_AUTO_CREATE_USER',
    'NO_ENGINE_SUBSTITUTION'
]

And don't forget to clear the cache after changing anything in the config file.

Upvotes: 1

Related Questions