0

In my laravel-application, I create an array like this:

$positions = Position::whereHas('jobs')
    ->with('jobs')
    ->get()
    ->groupBy('name')
    ->mapSpread(function ($position) {
         return $position->jobs->where('job_status_id', '=', '2')->pluck('industry');
     })

this returns an array, which looks like this: (I've made a dd($positions))

Illuminate\Support\Collection {#1280 ▼
#items: array:9 [▼
  "Engineer" => Illuminate\Support\Collection {#1279 ▶}
  "Analyst" => Illuminate\Support\Collection {#1274 ▼
     #items: array:1 [▼
       0 => App\Industry {#1294 ▶}
     ]
   }
  "Receptionist" => Illuminate\Support\Collection {#1304 ▶}
  "Programmer" => Illuminate\Support\Collection {#1306 ▼
     #items: array:2 [▶]
   }
  ]
}

Now, I want to display the key values and the amount of jobs the key value has in my blade view - for example "Programmer (2)"

I tried to do this:

@foreach($positions as $k => $v)

  @foreach ($v as $key => $value)
        {{ $value->name }}
  @endforeach

@endforeach

but this only returns the name of the industry, like for example "IT" or "Construction" (which I get from the Industry relation)

So how can I achieve that?

2 Answers 2

1

You try count() method for a collection

@foreach($positions as $k => $v)
 <div>{{ $k }} ({{ $v->count() }})</div>
@endforeach

Reference: https://laravel.com/docs/6.x/collections#method-count

Sign up to request clarification or add additional context in comments.

Comments

0

Count the element in the for loop and display it like this in the view

@foreach($positions as $k => $v)

  @foreach ($v as $key => $value)
        {{ $value->name }} {{ count($value->toArray()) }}
  @endforeach

@endforeach

Remove the toArray() if it gives error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.