1👍
✅
Seems that there aren’t much to improve since you need to get data per gender and per age group. I have made a few changes to the code but nothing special.
<?php
namespace App\Http\Controllers;
use App\Individual;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class IndividualDashboardController extends Controller
{
//Get User Gender name
private function get_gender ()
{
return Individual::select('gender')->get();
}
//Count user by gender
private function count_gender()
{
$gender = $this->get_gender();
if(!empty($gender)){
foreach ($gender as $sex) {
$count[] = Individual::where('gender', $sex)->count();
}
}
return json_encode($count);
}
//Get Individuals Age Groups
private function get_age_group ()
{
return Individual::select('age_group')->get();
}
//Count Individual by gender
private function count_age_group()
{
$age_groups = $this->get_age_group()->toArray();
if(!empty($age_groups)){
foreach ($age_groups as $age_group) {
$count[] = Individual::where('age_group', $age_group)->count();
}
}
return json_encode($count);
}
/**
* Display a listing of the resource.
*/
public function index()
{
return view('individuals.dashboard', [
'gender' => $this->get_gender(),
'count_gender' => $this->count_gender(),
'age_group' => $this->get_age_group(),
'count_age_group' => $this->count_age_group(),
]);
}
}
```
Source:stackexchange.com