Home > Enterprise >  Laravel: how to handle count in query
Laravel: how to handle count in query

Time:05-26

Currently I'm getting the list of table list in controller. And i got it successfully..But there is a problem, i return a list and a total.But when there is value package my count() is limited by skip - take .So I have to split it into 2 queries. Is there any way to combine those 2 queries into one to compact the code. Please give me your opinion. Thanks.

public function listData(Request $request)
    {
        $package = $request->package;
        $userId = [1,3];
        $list = List::whereIn('user_id', $userId)
        ->when(!empty($package), function ($query) use ($package) {
            $query->where('idPackage', '=' . $package);
        })->orderBy('created_at', 'DESC')->skip(0)->take(20)->get()->toArray();


        $count = List::whereIn('user_id', $userId)
        ->when(!empty($package), function ($query) use ($package) {
            $query->where('idPackage', '=' . $package);
        })->count();

        return response()->json([
            'list'  => $list,
            'total' => $count
        ], 200);
    }

CodePudding user response:

This is so simple.. I think you should try this:

public function listData(Request $request)
    {
        $package = $request->package;
        $userId = [1,3];
        $list = List::whereIn('user_id', $userId)
        ->when(!empty($package), function ($query) use ($package) {
            $query->where('idPackage', '=' . $package);
        });
        $count = $list->count();
        $listData = $list->orderBy('created_at', 'DESC')->skip(0)->take(20)->get()->toArray();
    
        return response()->json([
            'list'  => $listData,
            'total' => $count
        ], 200);
    }

good luck :))

  • Related