In this article, i will share with you how to export a very large CSV file in laravel using the lazycollection and cursor with example. you all face many time issues with an export very large file. if you try to export 10M record in one call then the PHP/apache
did not handle this type of large data with one call because of some memory issue.
But laravel provides a very helpful functionality for how to handle this type of issue and run time manage memory help of LazyCollection and cursor.
Here, i provide a simple code for how to export/download a very large CSV in 10sec.
I test this example with the 10M records.
In the first step, we need to create one route in our laravel route file.
// Route for export csv
Route::get('download-csv', [ExportCSVController::class, 'download'])->name('download-csv');
Now, we need to create ExportCSVController.php
file in app/Http/Controllers
directory and write there the following code.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class ExportCSVController extends Controller
{
public function download(Request $request)
{
// get the request value
$input = request()->all();
// set header
$columns = [
'Name',
'Email',
'Phone No.',
'Created Date',
];
// create csv
return response()->streamDownload(function() use($columns, $input) {
$file = fopen('php://output', 'w+');
fputcsv($file, $columns);
$data = User::select(
'name',
'email',
'phone_no',
'created_at'
)
->orderBy('id', 'desc');
$data = $data->cursor()
->each(function ($data) use ($file) {
$data = $data->toArray();
fputcsv($file, $data);
});
fclose($file);
}, 'AllUsersCSV'.date('d-m-Y').'.csv');
}
}
Help of above code you can download million of records with a single click.
i hope you like this article.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
How to create google firebase project
Today, we are share with you how to crea...How to get Last Record From leftJoin Table in Laravel7?
In this article i will share with you on...How to Convert Comma Separated String into an Array in JavaScript
Use the split() Method You can use th...How to Convert a Date to Timestamp in PHP
Use the strtotime() Function You can...How to sort an associative array by key in PHP
Use the PHP ksort() and k...