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

Hello_World's avatar

Get Data within two date range in laravel 5.1

I have some users who need to pay some amount in monthly basis. I need to extract those information who paid/not within given date range. If the user select Jan-2020 - Jun-2020, it should get all the information within those date. I was able to get those values. But my requirement is, if a user did not pay in a month (suppose march-2020) it will return 0. Right now its only getting available data. I don't want to use any loop to get those data. I am looking for single query solution. Here is my query that i am using right now

       $studentPaymentDetails = Student::select('student_id', 'student_name', 'system_generated_student_id')
            ->with(
                [
                    'received_payment' => function ($query) {
                        $query->select(
                            'received_student_payment_id',
                            'student_id',
                            'received_amount_by_bank',
                            'received_time'
                        )
                        ->whereBetween('received_time', [$dateFrom, $dateTo])
                        ->orderBy('received_time');
                    }
                ]
            )
            ->if($Class, 'class_id', "=", $Class)
            ->if($Group, 'stu_group', "=", $Group)
            ->if($Section, 'section_id', "=", $Section)
            ->if($BranchShiftVersion, 'institute_branch_version_id', "=", $BranchShiftVersion)
            ->if($Branch, 'branch', "=", $Branch)
            ->if($Year, 'acc_year', "=", $Year)
            ->where('status', 1)
            ->orderBy('roll_no')
            ->get();

Is it possible to arrange this structure using only query! Or i need to loop through the data and make another array separately to structure my information!

0 likes
3 replies
ederson's avatar

You could use a relation between receiveduserpayments and users

Or use join() to connect the two tables based on receiveduserpayments.user_id and users.id

Hello_World's avatar

@ederson I have no problem getting the data using relation/looping through. As i said, if there is no data for a month, it need to show 0 by default, And is there any way i can get that using eloquent/query builders!

Please or to participate in this conversation.