Laravel: Rendering CSV data in an HTML table

Updated: February 14, 2024 By: Guest Contributor Post a comment

Overview

In this tutorial, we will explore how to render CSV data within an HTML table using Laravel, a popular PHP framework known for its simplicity and elegance in web development. Whether you’re dealing with data exports, report generation or simply displaying a user-friendly format of your data, knowing how to convert CSV files to HTML tables is a nifty skill within the Laravel ecosystem.

First things first, ensure you have a Laravel project setup. If not, create one using Composer by running the following command in your terminal:

composer create-project --prefer-dist laravel/laravel CSVtoHTMLTable

Sample CSV Data

Here’s a simple example of what the CSV data might look like:

Name,Email,Age
John Doe,[email protected],30
Jane Doe,[email protected],25
Mike Smith,[email protected],28

This CSV file includes three columns (Name, Email, Age) and three rows of data.

Step-by-Step Instructions

Step 1: Fetching CSV Data

The initial step involves fetching your CSV data. In this tutorial, we will assume that the CSV file is stored locally in the storage/app directory (you can use the sample CSV data in the section above for this). Here is how you can fetch your CSV data in a Laravel app:

$path = storage_path('app/myData.csv');
$file = fopen($path, 'r');
$data = [];
while (($line = fgetcsv($file)) !== FALSE) {
  $data[] = $line;
}
fclose($file);

This piece of code opens the CSV file for reading and iterates over each line, storing it in an array. Ensure you close the file after reading to avoid memory leaks.

Step 2: Passing Data to View

Now that you have your CSV data in an array, the next step is to pass this data to your view. In Laravel, this is easily managed via controllers. Here is a simple controller method to pass the data:

public function showCSVData() {
  $path = storage_path('app/myData.csv');
  $file = fopen($path, 'r');
  $data = [];
  while (($line = fgetcsv($file)) !== FALSE) {
    $data[] = $line;
  }
  fclose($file);
  return view('csvTable', compact('data'));
}

Add this method to any of your controllers and remember to import the necessary classes at the top of your file.

Step 3: Creating the View

With the data ready, let’s focus on creating our HTML table in the view. Create a new view file named csvTable.blade.php in the resources/views directory. Here’s a basic example of how your HTML table might look:

<table border="1">
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
    </tr>
  </thead>
  <tbody>
  @foreach($data as $row)
    <tr>
      @foreach($row as $cell)
        <td>{{ $cell }}</td>
      @endforeach
    </tr>
  @endforeach
  </tbody>
</table>

This example assumes a CSV with three columns. The @foreach directives are used to iterate over the data array and output each row and cell into the table. Adjust the <th> elements based on the number of columns in your CSV file.

Step 4: Implement CSVController

Next, let’s create the CSVController. You can generate a new controller using the Artisan CLI command:

php artisan make:controller CSVController

Then, open the newly created controller file located at app/Http/Controllers/CSVController.php, and add the following code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CSVController extends Controller
{
    public function showCSVData()
    {
        $path = storage_path('app/myData.csv');
        $file = fopen($path, 'r');
        $data = [];
        while (($line = fgetcsv($file)) !== FALSE) {
            $data[] = $line;
        }
        fclose($file);
        
        return view('csvTable', compact('data'));
    }
}

his controller method showCSVData reads the CSV file myData.csv from the storage/app directory, iterates through each line of the file using fgetcsv, and stores each line as an array in the $data array. It then passes this array to the view named csvTable.

Step 5: Routing

Ensure you have the correct route set up in routes/web.php to handle the URL that displays the CSV data in an HTML table:

use App\Http\Controllers\CSVController;

Route::get('/csv-data', [CSVController::class, 'showCSVData']);

Visiting /csv-data in your browser will now render the CSV data in an HTML table format.

Conclusion

In conclusion, Laravel makes it incredibly simple to work with different types of data, including CSV. By fetching your data, passing it to the view, and utilizing Blade’s templating to generate dynamic content, you can effectively render CSV data into an HTML table. This tutorial aims to provide a foundation upon which you can build more complex data-driven applications within the Laravel framework.