Skip to content

Passing LazyCollection to Blade view causes query to execute twice #39003

Closed
@awebartisan

Description

@awebartisan
  • Laravel Version: 8.61.0
  • PHP Version: 7.4.22
  • Database Driver & Version: MySQL v8

Description:

When a LazyCollection instance is passed to Blade view and looped via @foreach directive, it causes the query to execute twice. Believe that its because of how foreach directive is compiled under the hood and how count and last record of the Countable is managed inside ManagesLoops file.

Steps To Reproduce:

  • Inside controller or route file
    $users = User::lazy();
    return view('welcome', ['users' => $users]);
  • Inside blade view
    @foreach($users as $user)
        <div>{{ $user->name }}</div>
    @endforeach
  • Queries detected using Ray
    image

GitHub Repo

https://github.com/awebartisan/lazy-collection-blade-query-bug

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions