Show only one data from duplicate data

how can i show only one data from same data when doing loop in laravel

result now

{"Id":12,"Code":"","Name":"Cordoba","Status":"true"}
{"Id":12,"Code":"","Name":"Cordoba","Status":"true"}
{"Id":16,"Code":"","Name":"Verona","Status":"true"}
{"Id":16,"Code":"","Name":"Verona","Status":"true"}
{"Id":16,"Code":"","Name":"Verona","Status":"true"}

i want to show like this

{"Id":12,"Code":"","Name":"Cordoba","Status":"true"}
{"Id":16,"Code":"","Name":"Verona","Status":"true"}

the script that I have tried

@foreach ($list as $list)
    @foreach ($collection->where('Id', $list->item->Collection) as $col)
        {{ $col }}<br>
    @endforeach
@endforeach

my controller
public function product_list($id){

    $list = ProductList::where('CategoryId',$id)
    ->where('Status',true)->with('item')->get();

    $collection = Collection::where('Status',true)->get();
     
     //try like this but not succes
    //$collection = Collection::where('Status',true)
    //->select('Id',DB::raw('count(*) as total'))
    //->groupBy('Id')
    //->get();

    return view('frontend/products/product-list',compact('menu','submenu','list','collection'));

>Solution :

In your controller

$list = ProductList::where('CategoryId',$id)
    ->where('Status',true)->with('item')->get();

$ids = [];

foreach($list as $list){
    array_push($ids, $list->item->Collection); 
    // if item->Collection returns id.
    // If it don't then access its id like item->Collection->Id
}

$ids = array_unique($ids);

$collection = Collection::where('Status',true)->whereIn('Id', $ids)->get(); // send it to frontend and loop through

In view

@foreach ($collection as $col)
    {{ $col }}<br>
@endforeach

Leave a Reply