John Davidson

php - Laravel - export to csv return blank list

0 comments
Message:


i want to make custom in my laravel project a button to export list of customers...
The route is ok, blade file is ok, the csv is exported but without users details, last_name, first_name and email...


Somebody know why? I am beginner in laravel


     public function exportCsv(Request $request) {
$fileName = 'tasks.csv';
$users = User::role('staff');
$headers = array(
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=$fileName",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0"
);

$columns = array('first_name', 'last_name', 'email');

$callback = function() use($users, $columns) {
$file = fopen('php://output', 'w');
fputcsv($file, $columns);

foreach ($users as $user) {
$row['first_name'] = $user->first_name;
$row['last_name'] = $user->last_name;
$row['email'] = $user->email;

fputcsv($file, array($row['first_name'], $row['last_name'], $row['email']));
}

fclose($file);
};

return response()->stream($callback, 200, $headers);
}


My Answer:
It looks like you are missing the `get()` method to actually fetch the users from the database. Try updating your code like this:

php
public function exportCsv(Request $request) {
$fileName = 'tasks.csv';
$users = User::role('staff')->get(); // Add get() method here
$headers = array(
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=$fileName",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0"
);

$columns = array('first_name', 'last_name', 'email');

$callback = function() use($users, $columns) {
$file = fopen('php://output', 'w');
fputcsv($file, $columns);

foreach ($users as $user) {
$row['first_name'] = $user->first_name;
$row['last_name'] = $user->last_name;
$row['email'] = $user->email;

fputcsv($file, array($row['first_name'], $row['last_name'], $row['email']));
}

fclose($file);
};

return response()->stream($callback, 200, $headers);
}


By adding the `get()` method after `User::role('staff')`, you are actually fetching the users from the database and then looping through them to export their details to the CSV file.

Rate this post

3 of 5 based on 9731 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us