Laravel: Simple creation of csv file in laravel?

Creating a simple CSV file in Laravel can be done using the built-in Laravel functions and PHP's fputcsv function to write data to the file. Here are the steps to create a CSV file in Laravel:

  1. Create a Route:

    First, create a route that will trigger the CSV creation. Open the routes/web.php file and add a new route:

    php
  • // routes/web.php Route::get('/generate-csv', 'CsvController@generateCsv');
  • Create a Controller:

    Next, create a controller to handle the CSV generation. You can generate a controller using the php artisan make:controller command:

    bash
  • php artisan make:controller CsvController

    This command will generate a CsvController.php file in the app/Http/Controllers directory.

  • Implement the CSV Generation Logic:

    Open the CsvController.php file and add a method to generate the CSV file:

    php
    1. // app/Http/Controllers/CsvController.php use Illuminate\Http\Request; use Illuminate\Support\Facades\Response; use Illuminate\Support\Facades\Storage; class CsvController extends Controller { public function generateCsv() { // Define the CSV file name $filename = 'example.csv'; // Define the CSV file header row $headers = ['Name', 'Email', 'Phone']; // Define the CSV data (example data) $data = [ ['John Doe', 'john@example.com', '123-456-7890'], ['Jane Smith', 'jane@example.com', '987-654-3210'], ]; // Create a CSV file and write the data to it $file = fopen(storage_path('app/' . $filename), 'w'); // Write the headers fputcsv($file, $headers); // Write the data foreach ($data as $row) { fputcsv($file, $row); } // Close the file fclose($file); // Return the CSV file as a download response return response()->download(storage_path('app/' . $filename), $filename, [ 'Content-Type' => 'text/csv', ]); } }

      In this example, we define the CSV file name, headers, and data. We then create the CSV file, write the headers and data to it, and return the CSV file as a download response.

    2. Access the CSV Generation Route:

      You can now access the CSV generation route by navigating to http://yourdomain.com/generate-csv in your web browser. This will trigger the generateCsv method in the CsvController, which will generate and download the CSV file.

    Remember to customize the CSV data and filename according to your application's requirements.

    Comments