To export data to a CSV file in Laravel, you can use a few different approaches. One common method is using the Laravel Excel
package, which simplifies the process of exporting and importing data. Here’s how you can do it:
You need to install the Maatwebsite/Laravel-Excel
package via Composer.
composer require maatwebsite/excel
You can create an export class that will handle the data you want to export.
php artisan make:export UsersExport --model=User
This will create a new export class in app/Exports/UsersExport.php
.
In the UsersExport
class, you need to specify the collection of data you want to export. Here’s an example:
namespace App\Exports; use App\Models\User; use Maatwebsite\Excel\Concerns\FromCollection; class UsersExport implements FromCollection { /** * @return \Illuminate\Support\Collection */ public function collection() { return User::all(); } }
In your controller, you can now trigger the export process.
namespace App\Http\Controllers; use App\Exports\UsersExport; use Maatwebsite\Excel\Facades\Excel; use Illuminate\Http\Request; class UserController extends Controller { /** * Export users to CSV. * * @return \Illuminate\Support\Facades\Response */ public function export() { return Excel::download(new UsersExport, 'users.csv'); } }
Finally, create a route to handle the export request.
use App\Http\Controllers\UserController; Route::get('export-users', [UserController::class, 'export']);
Now, when you visit yourdomain.com/export-users
, the users’ data will be downloaded as a CSV file.
If you prefer not to use an external package, you can use native PHP functions like fputcsv
. Here’s a quick example:
namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Response; class UserController extends Controller { public function export() { $users = User::all(); $filename = "users.csv"; $handle = fopen($filename, 'w+'); fputcsv($handle, ['ID', 'Name', 'Email']); foreach ($users as $user) { fputcsv($handle, [$user->id, $user->name, $user->email]); } fclose($handle); $headers = [ 'Content-Type' => 'text/csv', ]; return Response::download($filename, $filename, $headers); } }
This method is more manual but does not require additional dependencies.
Both methods will allow you to export data to a CSV file in Laravel.