Eden WebStudio
Eden WebStudio

Reputation: 788

How to return collection or array data to view after looping through foreach?

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>

Upvotes: 0

Views: 2134

Answers (3)

user1960364
user1960364

Reputation: 1999

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.

Upvotes: 1

Vinicius Luiz
Vinicius Luiz

Reputation: 132

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.

Upvotes: 1

Jono20201
Jono20201

Reputation: 3205

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.

Upvotes: 1

Related Questions