Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Freddie19's avatar

How to Filter Across Multiple Data Sources using a Parameter on Dashboard?

how do I filter data from parameters, for example I need data to filter from branch from dropdown with its params : /dashboard?branch=1 example.

this the Services i use :

class DashboardService
{
    public function dataIndex(string $branch = null): array
    {
        /**
         * branch select filter
         */
        $branches = Branch::all();

        /**
         * User role count
         */
        $roles = Role::whereIn('name', ['Cashier', 'Operator'])->pluck('name');

        $countUserByRole = [];
        foreach ($roles as $role) {
            $count = User::role($role)->count();
            $usersCountByRole[$role] = $count;
        }
        $totalVehicle = Vehicle::count();
        $totalUser = User::role('Customer')->count();

        /**
         * Membership
         */

        $totalRemainingQuota = UserMembership::sum('remaining_quota');
        $totalMembership = UserMembership::where('remaining_quota', '>', 0)
            ->distinct('user_id')
            ->count('user_id');


        /**
         * Branch
         */
        $totalBranch = Branch::count();

        /**
         * Product
         */
        $productTypes = Product::groupBy('product_type')->pluck('product_type');

        $totalProductsByType = [];
        foreach ($productTypes as $productType) {
            $count = Product::where('product_type', $productType)->count();
            $totalProductsByType[$productType] = $count;
        }

        $totalProduct = Product::count();
        $totalProductDiscount = Discount::count();

        return [
            'usersCountByRole' => $usersCountByRole,
            'totalUsers' => $totalUser,
            'totalBranch' => $totalBranch,
            'totalProduct' => $totalProduct,
            'totalProductDiscount' => $totalProductDiscount,
            'totalProductsByType' => $totalProductsByType,
            'totalMembership' => $totalMembership,
            'totalRemainingQuota' => $totalRemainingQuota,
            'totalVehicle' => $totalVehicle,
            'branchFilter' => $branches,
        ];
    }
}
0 likes
1 reply
martinbean's avatar
Level 80

@freddie19 Your code isn’t very efficient right now, because you’re calling Branch::all(), which is just going to fetch all rows from your database. If you have 50,000 branches, then that code is going to try and read all 50,000 into memory. You should therefore be using pagination to only show a subset at any one time.

For conditionally adding clauses to a query, you can use the when method: https://laravel.com/docs/queries#conditional-clauses

Please or to participate in this conversation.