PLATFORM
  • Tails

    Create websites with TailwindCSS

  • Blocks

    Design blocks for your website

  • Wave

    Start building the next great SAAS

  • Pines

    Alpine & Tailwind UI Library

  • Auth

    Plug'n Play Authentication for Laravel

  • Designer comingsoon

    Create website designs with AI

  • DevBlog comingsoon

    Blog platform for developers

  • Static

    Build a simple static website

  • SaaS Adventure

    21-day program to build a SAAS

Question By
Unsolved

Prevent foreach loop from repeating -laravel

alkhatibsyr

Aug 22nd, 2021 05:29 AM

I fetch services from our database through code

'services' =>  Service::with('seller.user', 'seller.level', 'subcategory')
            ->whereHas('seller', function ($query) {
                return   $query->where('status', 'active');
            })
            ->Where('tags', 'like', '%' . $this->tag . '%')
            ->withAvg('review', 'rating')
            ->withCount('review')
            ->paginate(20)

How to ignore duplicate subcategories in the loop

 @foreach ($services as $service)
        $service->subcategory->name
        @endforeach

I get a lot of duplicate subcategories

bobbyiliev

Sep 2nd, 2021 01:25 AM

Hello,

In this specific case, if you want to get a list of the subcategories only, then I could suggest not looping through your services and then listing each subcategory of each service, but instead just return a list of your subcategories and loop through them directly.

For example:

$subcategories = Subcategory::all();

And then loop through them:

@foreach($subcategories as $subcategory)
    $subcategory->name
@endforeach

Hope that this helps.

Regards,

Bobby