Create and save csv to storage in Laravel

Create and save csv to storage in Laravel

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Creating CSV Files and Storing Them in Laravel Storage

Many developers encounter a specific workflow pattern: generate a CSV file from database records, store that physical file on the filesystem, and then persist a reference to it in the database. The challenge often lies in bridging the gap between generating a dynamic response stream and creating a static file object within Laravel's storage system.

The core issue in the provided example stems from mixing two fundamentally different approaches: streaming responses versus file writing. The original code uses fopen('php://output', 'w') to write directly to the browser output. This creates a stream that exists only for the duration of the HTTP request. You cannot store a stream object in the filesystem or pass it to a model like UserDocument.

To solve this, you must decouple the file generation logic from the response sending logic. Instead of writing to php://output, write directly to the disk using Laravel's Storage facade. This ensures the file physically exists on the server before you attempt to save a record referencing it in your database.

Writing Directly to Storage

Laravel provides a unified interface for managing files via the Storage facade. When generating a CSV, define your headers and data columns first, then utilize Storage::path() to get the absolute path where you want to write the file.

Here is how you can refactor the controller logic to write the file to disk:

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;

public function updatePaymentConfirm(Request $request)
{
    $users = User::all();
    $fileName = 'test.csv';
    
    // Define headers for the CSV
    $columns = ['First Name', 'Email'];

    // Get the absolute path for the file within the storage directory
    // This creates the path relative to the public disk (e.g., /storage/app/public/uploads/test.csv)
    $filePath = Storage::disk('public')->path('uploads/' . $fileName);

    // Open the file specifically for writing on the disk
    $file = fopen($filePath, 'w');

    // Write headers
    fputcsv($file, $columns);

    // Write data rows
    foreach ($users as $user) {
        $row = [
            'First Name' => $user->first_name,
            'Email'      => $user->email
        ];
        fputcsv($file, array_values($row));
    }

    fclose($file);

    // Now that the file exists on disk, we can interact with it like any other file
    return response()->download($filePath, $fileName)
        ->header('Content-Type', 'text/csv')
        ->withHeaders([
            'Content-Disposition' => 'attachment; filename="' . $fileName . '"',
            'Pragma' => 'no-cache',
            'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
            'Expires' => '0',
        ]);
}

In this approach, Storage::disk('public')->path() resolves the URL path based on your configuration in config/filesystems.php. By opening the file at this resolved path, you are writing directly to the disk rather than streaming to the browser immediately.

Saving a Reference in the Database

Once the file is successfully written to the filesystem, you can proceed with updating your database. The error Call to a member function storeAs() on resource suggests an attempt to call a method on a raw file handle (resource) instead of a Laravel collection or model. In the corrected flow above, we are not using storeAs because we generated the file content manually. We simply have the path string.

To persist this in your database, you need a model that tracks the file. Assuming you have a UserDocument model (or similar), you would save it after the file write operation completes:

$fileModel = new UserDocument();
$fileModel->name = $fileName;
// Store the relative path or absolute URL depending on your application needs
$fileModel->file_path = '/storage/app/public/uploads/' . $fileName; 
// Or simply store the filename if you handle URL reconstruction in views
$fileModel->file_path = 'uploads/' . $fileName; 

// Ensure you are saving to the correct database connection if applicable
$fileModel->save();

// Return a success response to the user without triggering a download
return back()
    ->with('success', 'File has been uploaded and record saved.')
    ->with('file', $fileName);

Important Considerations and Trade-offs

There are several architectural decisions to keep in mind when implementing this pattern. First, consider file size limits. Writing large CSV files directly using fopen and loops can consume significant memory if not handled carefully. For massive datasets, buffering the output or using streams more explicitly is advisable to prevent memory exhaustion.

Second, ensure that your storage disk permissions are correct. The application must have write access to the directory where you are saving the file. Common issues arise on shared hosting environments where the storage/app/public/uploads directory does not have the correct permissions (usually 755 or 775 depending on the OS and PHP configuration).

Finally, be aware of the lifecycle of the file. If you delete the database record associated with the file, you must also delete the physical file from storage to avoid leaving orphaned data behind. You can create a delete method in your model or controller that uses Storage::disk('public')->delete($fileModel->file_path) to handle this cleanup automatically.

By separating the file generation logic from the response delivery and ensuring you are writing to a resolved filesystem path, you can reliably build CSV export features that integrate seamlessly with your database schema.

Our network