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

nomanshah's avatar

count data in table

table booking

id 1 2 3 4

staff_id 4 4 5 5

first i select all data from staff table then every staff against data get from booking table and count all bookings but not give me correct record count....count record is only 2 and realy record in table is 4 you see it in above table plzzz any one guide me how can get correct count from this table tanx

$staff = staff::all()->get();

foreach ($staff as $staffs ) {

$booking = booking::where('staff_id' , $staffs ->id)->count(); }

0 likes
3 replies
RayC's avatar
RayC
Best Answer
Level 10

If it is returning 2 that is correct. You are only retrieving the records for 1 staff member ID.

To get the total of staff members you should use:

$staff = Staff::all()->count();

If you did it like this:

$staffs = Staff::all();

foreach ( $staffs as $staff ) {
    echo Booking::where('staff_id' , $staff->id)->count()."<br />";
}

// Should output:
// 2
// 2

It also appears you only have 4 staff members based on your post. But you have 4 records in the other table with staff member 4 and staff member 5.

Do you have a staff member with ID 5?

Hope this helps.

Regards, Ray

nomanshah's avatar

in booking table booking id 1 and 2 for staff member 4 and booking id 3 and 4 for staff member 5, so total booking id is 4 but i count it return false result 2......i require 4 result from booking table

Please or to participate in this conversation.