In this post we will learn how to add a CSV export feature in Laravel project. We will export data from Users table in this code example. So, lets begin.

First lets add a form that will submit the CSV export post request to Laravel.

<form action="{{ route('users.csv') }}" method="post">
    @csrf
    <button type="submit">Export Users to CSV</button>
</form>

Next we need to define route to receive out post request for CSV export. Make sure that you change Controller and route name as required.

Route::Post('user/export', 'UserController@export')->name('users.csv');

Finally here is the method that actually done the export. This method belongs to UserController

    public function export(Request $request)
    {

        $headers = [
            'Content-Type' => 'application/csv',
            'Content-Disposition' => 'attachment; filename=users.csv',
            'Content-Transfer-Encoding' => 'UTF-8',
        ];

        $users = User::orderBy('name', 'asc')->get();

        return response()->stream(function () use ($users) {
            $csvFile = fopen('php://output', 'w');
            fputcsv($csvFile, ['Name', 'Email']); // add title to csv file

            foreach ($users as $user) {
                fputcsv($csvFile, [$user->name, $user->email]);
            }

            fclose($csvFile);

        }, 200, $headers);

    }

And that’s about it. You should now be able to export CSV file.