befreeforlife
befreeforlife

Reputation: 511

Work with foreach in Laravel: delete same values

I found way to delete duplicate values in the result but it doesn't work correctly. How to fix it?

I have next code:

    public function getListPositionByApplication($app_id){
    // $app_id = \Request::input('app_id');
    $list = SparePartApplicationPositionProvider::where('app_id',$app_id)->with(['provider','application_position'])->orderBy('apos_id')
            ->get();
            $aa=0;
            foreach ($list as $value) {
                if($value->apos_id==$aa){
                    $value->application_position->name_detail='----';
                }
                $aa = $value->apos_id;
                 Log::info($value->apos_id);
            }

    return $list;
}

Log::info give next information: 26,26,26,26,26,26,27,27,27,27,27,27,28 but $value->application_position->name_detail have '----' in all cases with the exception of last value

Upvotes: 0

Views: 171

Answers (2)

user8824269
user8824269

Reputation:

You can try collection unique() method.

https://laravel.com/docs/master/collections#method-unique

Upvotes: 1

Paul M
Paul M

Reputation: 451

@Hussein is right, group by the common column and don't do a foreach. Let the Eloquent DB do the heavy lifting. Notice the callback where you include your second table.

    $list = SparePartApplicationPositionProvider::where('app_id',$app_id)
->with(['provider','application_position' => function ($query){
    $query->groupBy('name_detail');
    }])
->orderBy('apos_id')
->get();

Upvotes: 1

Related Questions