ChrisMellor's avatar

Passing LazyCollection Data to View

Hi,

I am trying to pass data from a LazyCollection into a view, but I can't seem to accomplish it.

I am getting a row from a CSV file and want to parse the data and display it in a table. I am trying to accomplish this by using a package by Spatie -- Simple Excel Reader.

First, I'm getting the rows from the CSV file

Route::get('/csv', function () {
    $rows = SimpleExcelReader::create(storage_path('app/test.csv'))
        ->getRows();
});

This is what returns a LazyCollection

From a ddd()

Illuminate\Support\LazyCollection {#298 ▼
  +source: Closure() {#297 ▼
    class: "Spatie\SimpleExcel\SimpleExcelReader"
    this: Spatie\SimpleExcel\SimpleExcelReader {#267 …}
    file: "/Users/chris/csv-test/vendor/spatie/simple-excel/src/SimpleExcelReader.php"
    line: "150 to 161"
  }
}

Of course, I can run this through a foreach() and get an array back

foreach($rows as $row) {
	dump($row);
}

Result

array:4 [
  "name" => "Chris"
  "email" => "[email protected]"
  "password" => "password"
  "role_id" => "1;2;3"
]

So I thought I could just pass $rows to a view and for a @foreach in the Blade view, but doing produces a blank page.

return view('csv-view')->with([
    'rows' => $rows,
]);
@foreach($rows as $row)
	{{ $row->name }}
@endforeach

So it would seem the data isn't being passed to the view, but this is where I got stuck and spent far too much time debugging it that told myself I need some help 😂

Hopefully, I can get some assistance in figuring this out or tell me where I am going wrong.

Thanks!

0 likes
2 replies
sr57's avatar

I never work with Lazy Collection, till now, have you try with a short sample of date and Collection, just to be sure the the pb comes from Lazy C?

ChrisMellor's avatar

I believe a LazyCollection is no different than a regular Collection, except it does some wizardry in the background to cut down memory usage -- there are also a few methods that won't work on it, but these are well documented.

I did figure it out eventually, I basically just chained the toArray() method to the SimpleExcelReader class and called the property in the Blade view as an array instead of an object -- $row['name']

Please or to participate in this conversation.