QuickBen
QuickBen

Reputation: 33

Foreach loop not going through correctly

I have a form to mark employees' attendance that HR fill in which is looped over every current employee. I need it to show the current values where attendance is marked in the database, otherwise it should be blank.

In my controller I query the existing results:

$results = Attendance::where('Sdate', '=', date("Y-m-d", strtotime($TheDate))) ->get();

Then loop through them to get the employee details:

foreach($results as $result)
{
    $contractors = DB::table('contractors')
        ->where('contractors.AreaPosition', '=', $department)
        ->where('PRN', '!=', $result->PRN)->get();
    $employees = DB::table('current_employees')
        ->where('current_employees.AreaPosition', '=', $department)
        ->where('PRN', '!=', $result->PRN)->get();
    $showEmployees = array_merge($contractors, $employees);
}

This should exclude all employees who have a record saved in attendance for that date, however it doesn't seem to be looping correctly. It will exclude some results, but not all. If I return the results variable I get the correct list of records so I know that part is working correctly.

What I'm looking to achieve in my view is something like:

@foreach($attendance as $results)

Show form where there's an existing record for this date and department

@endforeach



@foreach($employees as $employee)

Show form for all employees in this department (but should exclude results where there is a record in attendance)

@endforeach

Upvotes: -3

Views: 206

Answers (2)

QuickBen
QuickBen

Reputation: 33

This was answered for me on Laracasts.

What I needed to do was create a list of the variable to check against (employee number)

    $PRNs = Attendance::where('Sdate', '=', date("Y-m-d", strtotime($TheDate)))->lists('PRN');

And then use Laravel's whereNotIn, checking against the list.

    $contractors = DB::table('contractors')
        ->where('contractors.AreaPosition', '=', $department)
        ->whereNotIn('PRN', $PRNs)
        ->get();

Upvotes: 0

Sameer Shaikh
Sameer Shaikh

Reputation: 7834

The problem with your code is you are saving the result in a variable and not in an array. Your solution would be to store the data in an array

foreach($results as $result)
{
    $contractors[] = DB::table('contractors') ->where('contractors.AreaPosition', '=', $department) ->where('PRN', '!=', $result->PRN) ->get(); $employees = DB::table('current_employees') ->where('current_employees.AreaPosition', '=', $department) ->where('PRN', '!=', $result->PRN) ->get(); $showEmployees = array_merge($contractors, $employees);
}

Try printing contractors array and see what happens.I hope this works

Upvotes: 0

Related Questions