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?
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.