0

Context: I am trying work out the total number of hours an employee has worked an appointment and show the sum by employee in the blade view. I can successfully sum up the hours for $starts_at minus $ends_at dates for each each $EmployeeHours. However when I dd(); i only see the last object and not a collection.

When I try to send data to view in a @foreach loop I get error:

array_merge(): Argument #2 is not an array

When I save to a table in the DB, it successfully iterates through and saves each $EmployeeHours I expect.

Problem is I do not want to save the results of the query to DB, I want to display to blade only as it is only a query for a user report to be extracted.

$EmployeeHours = DB::table('appointment_employee')
        ->join('appointments', 'appointment_id', '=', 'appointments.id')
        ->join('employees', 'employees.id', '=', 'appointment_employee.employee_id')
        ->join('users', 'users.id', '=', 'employees.user_id')
        ->where('role_id', '=', '1')
        ->get()->groupby('id');

        $results=[];
        foreach($EmployeeHours as $EmployeeHour)
        {

                $duration = [];

                foreach($EmployeeHour as $collection) 
                {

                $date1      = $collection->starts_at; 
                $date2      = $collection->ends_at;

                $start      = Carbon::parse($date1);
                $end        = Carbon::parse($date2);

                $length     = $start->diffInMinutes($end)/60;
                $duration[] = $length;  

                }

                $totalHours = array_sum($duration);         

//I think here is where I am going wrong possibly
            $results = [
            'totalHours' => $totalHours,                
            'employee_name' => $collection->first_name. " ".$collection->last_name,                     
            ];  


        }   
            dd($EmployeeHour);  


        return view ('admin.invoices.reporting.employeeHours',$results);

Here is the blade view

@foreach($results as $result)
                        <tr>
                            <td>{{ $result->employee_name }}</td>
                            <td>{{ $result->totalHours }}</td>
                        </tr>
                    @endforeach 

I have also tried without foreach loop in blade and it returns the last object i,e .

<tbody>                     
                        <tr>
                            <td>{{ $employee_name }}</td>
                            <td>{{ $totalHours }}</td>
                        </tr>                           
                    </tbody>
2
  • Please append your question with the relative code from your view. Commented Apr 7, 2017 at 19:56
  • I have added the view code. Tried 2 approaches. The foreach loop in blade returns an error presumably because I am not returning a collection. If without the foreach, then it prints the last object. but I want an array. Thanks. Commented Apr 7, 2017 at 20:02

3 Answers 3

1

There are 2 things that stand out to me...

  1. You're replacing $results instead of appending to it.
  2. You're view data is being passed to the view incorrectly.

Try:

$results = [];
foreach ($EmployeeHours as $EmployeeHour) {
    $duration = [];
    $name = null;

    foreach ($EmployeeHour as $collection) {
        $date1      = $collection->starts_at;
        $date2      = $collection->ends_at;

        $start      = Carbon::parse($date1);
        $end        = Carbon::parse($date2);

        $length     = $start->diffInMinutes($end)/60;
        $duration[] = $length;

        if (is_null($name)) {
            $name = $collection->first_name . " " . $collection->last_name;
        }
    }

    $totalHours = array_sum($duration);

    // Notice I added [], this will append it to the array instead of replacing it.
    $results[] = [
        'totalHours'    => $totalHours,
        'employee_name' => $name,
    ];
}

// Notice I used `compact()` which is the same as doing ['results' => $results]
return view('admin.invoices.reporting.employeeHours', compact('results'));

I agree with Jono20201, you should refactor to take advantage of the Eloquent ORM.

Sign up to request clarification or add additional context in comments.

6 Comments

I have followed this and I am now getting a error: Trying to get property of non-object.
Oh, it's because your $results are being set outside of the nested loop... $collection is undefined.
Updated the answer to fix the name. It's not the most efficient approach, but without knowing the structure of your result set, it's all I can really advise.
I have tried above. No luck yet. I have done die and dump() and it returns this structure...array:2 [▼ 0 => array:2 [▼ "totalHours" => 0.5 "employee_name" => "Guy Scott " ] 1 => array:2 [▼ "totalHours" => 3 "employee_name" => "Janet Test" ] ]
Oh, right... You're working with an array, not an object... So you'd need to use $result['totalHours'] and $result['employee_name']. Also, I'd advise renaming totalHours to total_hours to keep your naming consistent.
|
1

You're setting $results to a new array each time, when really you want to add to the $results array each interation.

$results[] = [
    'totalHours' => $totalHours,                
    'employee_name' => $collection->first_name . " " . $collection->last_name,                     
]; 

ps. You should really try to refactor this into using Eloquent Models/Relationships rather than using the query builder.

Comments

1

You should to change this:

 $results = [
        'totalHours' => $totalHours,                
        'employee_name' => $collection->first_name. " " . $collection->last_name,                     
 ];  

to this:

 $results[] = [
        'totalHours' => $totalHours,                
        'employee_name' => $collection->first_name. " ".$collection->last_name,                     
 ];  

When you don't use brackets you're replacing your array values to your new value, using brackets you're appending to your array new values each iteration.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.