You can use the chunk method to break up the query into smaller chunks and process them one at a time. The chunk method takes two arguments, the first is the number of records to return in each chunk and the second is a callback function that will be called for each chunk. Inside the callback function you can loop through the records and process them as needed.
For example, you can modify your code to something like this:
$rows = Person::has('visit')
->with('unit', 'rank', 'visit', 'city', 'town', 'village')
->filter()
->oldest('code')
->chunk(500, function($people) {
foreach($people as $person) {
// Process each person here
}
});
Then in your view you can loop through the $rows variable to display the results.