Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Add File::lines($path) method #34187

merged 1 commit into from Sep 8, 2020


Copy link

@JosephSilber JosephSilber commented Sep 7, 2020

Many of the most useful scenarios for using lazy collections involves reading files line by line (see here for more details).

This PR adds a lines method to the Filesystem class, to lazily read the lines of a file:

$collection = File::lines($path);


With this in place, you can easily read Laravel's logs lazily (using the new chunkWhile method):

$pattern = '/^[\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d]/'; // starts with e.g. [2020-09-07 00:24:11]

$logs = File::lines(storage_path('logs/laravel.log'))
    ->chunkWhile(fn ($line) => ! preg_match($pattern, $line));

The $logs variable will now be a lazy collection, from which we can pull out a single log entry at a time.

@JosephSilber JosephSilber force-pushed the files-lines branch 2 times, most recently from 37da74d to d7b139c Compare Sep 7, 2020
Copy link

GrahamCampbell commented Sep 7, 2020

Lazy collections could be quite appropriate for paginating eloquent queries tbh. Currently there's an each method, but we could "go native" as it were, and have a way to do getLazy() or something.

@taylorotwell taylorotwell merged commit 154fef3 into laravel:8.x Sep 8, 2020
1 check passed
@JosephSilber JosephSilber deleted the files-lines branch Sep 8, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet
None yet

Successfully merging this pull request may close these issues.

None yet

5 participants